每有一对字符就可以让palindrome长度加2,最后看还有没有剩余的字符,有就加1即可,因为回文最多允许一个数量为奇数的字符。O(n)时间空间,代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int longestPalindrome(string s) { | |
int len = s.size(), res = 0; | |
unordered_set<char> set; | |
for(auto& c : s) | |
{ | |
if(set.find(c) != set.end()) | |
{ | |
set.erase(c); | |
res += 2; | |
} | |
else | |
set.insert(c); | |
} | |
return set.size()? 1 + res: res; | |
} | |
}; |
No comments:
Post a Comment