01.04. Palindrome Permutation
Description
Given a string, write a function to check if it is a permutation of a palin drome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words.
Example1:
Input: "tactcoa" Output: true(permutations: "tacocat"、"atcocta", etc.)
Solutions
Solution 1: Hash Table
Thinking
A palindrome permutation is about symmetry after rearrangement, not about building one. Enumerating permutations is unnecessary.
At most one character may have an odd count. It is enough to tally frequencies and count how many odds there are.
A hash table (Counter) yields all frequencies in one scan; then check that the number of odd counts is less than \(2\), matching sum(v & 1 ...) < 2.
We use a hash table \(cnt\) to store the occurrence count of each character. If more than \(1\) character has an odd count, then it is not a palindrome permutation.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the length of the string.
1 2 3 4 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
Solution 2: Another Implementation of Hash Table
Thinking
Full frequency counts are discarded after the test; only parity matters.
A set of characters that currently have an odd count is enough: delete on a second sighting, insert otherwise. The final set size is the number of odd frequencies, still equivalent to “at most one odd”, with a smaller constant.
We use a hash table \(vis\) to store whether each character has appeared. If it has appeared, we remove the character from the hash table; otherwise, we add the character to the hash table.
Finally, we check whether the number of characters in the hash table is less than \(2\). If it is, then it is a palindrome permutation.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the length of the string.
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |