算法笔记: leetcode#266 palindrome permutation

问题描述


解法


分析

Python 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
class :
def canPermutePalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
left = set()
for c in s:
if c in left:
left.remove(c)
else:
left.add(c)
return len(left) < 2

Java 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class {
public boolean canPermutePalindrome(String s) {
Set<Character> left = new HashSet<>();
for(int i = 0; i < s.length(); i++){
if(left.contains(s.charAt(i))){
left.remove(s.charAt(i));
}else {
left.add(s.charAt(i));
}
}
return left.size() < 2;
}
}

时间复杂度

O(n).

空间复杂度

O(1).

链接


266. Palindrome Permutation
(English version) Algorithm Notes: Leetcode#266 Palindrome Permutation