'Given a string, determine whether any permutation of it is a palindrome
I am trying to determine that whether any string is palindrome or not. For example, carrace should return true, since it can be rearranged to form racecar, which is a palindrome. daily should return false since there's no rearrangement that can form a palindrome. How can I solve this ?
Code:
string = 'racecar'
if string[::-1] == string:
print('palindrome')
Above code is working for single string , not for permutations
Solution 1:[1]
from itertools import permutations
def palindrome(s: str) -> bool:
return ''.join(reversed(s)) == s
def permutated_palindrome(s: str) ->:
return any(map(palindrome,
map(''.join, permutations(s))
))
Solution 2:[2]
Java concise version
boolean isPermutationPalindrome(String s){
Set<Character> charSet = new HashSet<>();
for ( char c : s.toCharArray() ) {
if (!charSet.contains(c))
charSet.add(c);
else
charSet.remove(c);
}
return charSet.size() <= 1;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Joe |
