classSolution: defcanPermutePalindrome(self, s: str) -> bool: ''' find all invalid characters check if they could form palindrom ''' defisValid(s): ifnot s: returnTrue if len(s) == 1: returnTrue l, r = 0, len(s)-1 while l < r: if s[l] != s[r]: returnFalse l, r = l+1, r-1 returnTrue deffindInvalid(s): counter = Counter(s) res = "" for ch, freq in counter.items(): print(freq, ch) if freq % 2: res += ch*freq # print(res) return res while s: s = findInvalid(s) if isValid(s): returnTrue else: returnFalse returnTrue
Only need to check if removing even number of characters, if the number of odd characters are greater than 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution: defcanPermutePalindrome(self, s: str) -> bool: dic = defaultdict(int) for c in s: dic[c] += 1 # return sum(v % 2 for v in dic.values()) < 2 count1 = 0 for val in dic.values(): if val % 2 == 1: count1 += 1 if count1 > 1: returnFalse returnTrue
time complexity: $O(n)$, n = len(s) space complexity: $O(n)$ reference: related problem: