C# - 1 pass, keep odd counter, no Set - 4 lines of code.


  • 0

    you can avoid using a Set and could use a counting array instead which should be slightly more efficient. Same basic idea, a palindrome will have at most 1 odd counted char, just keep track of the number of chars with odd counts. If this count is 0 or 1 you can form a valid palindrome.

    1 pass:

        public bool CanPermutePalindrome(string s) {
            int[] map = new int[256];
            int oddCnt = 0;
            foreach (char c in s) oddCnt += (++map[c] & 1) == 1 ? 1 : -1;
            return oddCnt <= 1;
        }
    

Log in to reply
 

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