首页 > 代码库 > Permutation Palindrome
Permutation Palindrome
Given a string, determine if a permutation of the string could form a palindrome.
For example,"code"
-> False, "aab"
-> True, "carerac"
-> True.
Analyse: use hash map
1 class Solution { 2 public: 3 bool canPermutePalindrome(string s) { 4 unordered_map<char, int> um; 5 for (char ch : s) 6 um[ch]++; 7 8 bool canPermute = true; 9 for (unordered_map<char, int>::iterator ite = um.begin(); ite != um.end(); ite++) {10 if (ite->second % 2) {11 if (!canPermute) return false;12 else canPermute = false;13 }14 }15 return true;16 }17 };
Analyse: use A[ch]. There are 128 characters in ASCII, we can convert a char to int automatically.
1 class Solution { 2 public: 3 bool canPermutePalindrome(string s) { 4 vector<bool> charOccurenceBool(128, false); 5 for (char ch : s) 6 charOccurenceBool[ch] = !charOccurenceBool[ch]; 7 8 int count = 0; 9 for (int i = 0; i < charOccurenceBool.size(); i++) {10 if (charOccurenceBool[i]) count++;11 }12 return count < 2;13 }14 };
Permutation Palindrome
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。