My simple C++ solution, using a hash-like data structure


  • 5
    L
    bool canPermutePalindrome(string s) {
        int dict[256] = {0};
        for (auto c: s)
            dict[c]++;
        int cnt = 0;
        for (int i=0; i<256; i++){
            if (dict[i] % 2 != 0)   cnt++;
        }
        
        return cnt<=1;
    }

  • 0
    S

    nice. you could as well break when cnt becomes > 1


  • 0
    L

    good suggestion. thanks


  • 0
    I

    I am so sorry for my question.
    I am very new to programming.
    can you clarify for me what auto c: s and dict[c]++ do?
    And how we understand what letter/string is what?


  • 0
    S

    @isalirezag
    auto c : s iterates through the passed string s.
    dict[c]++ increments the counter to move to the next index .
    He is using 256 cause extended ascii table runs from 0 -255;
    so "a" get stored at dict[97] , b gets stored at dict[98] so on and so forth.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.