알고리즘/codefights
18>palindromeRearranging
Diademata
2017. 7. 2. 22:27
반응형
Given a string, find out if its characters can be rearranged to form a palindrome. Example For inputString = "aabb", the output should be palindromeRearranging(inputString) = true. We can rearrange "aabb" to make "abba", which is a palindrome. |
code>>
bool palindromeRearranging(std::string inputString) {
int alphabat[27] = { 0, };
for (int i = 0; i < inputString.size(); i++)
{
alphabat[inputString[i] - 'a']++;
}
int count = 0;
for (int i = 0; i < 27; i++)
{
count += alphabat[i] % 2;
}
return inputString.size() % 2 == count;
}
비트 연산으로 푼 풀이들
int A[256];
bool palindromeRearranging(std::string inputString) {
for(char i:inputString)
++A[i];
int c = 0;
for(int i = 0; i < 256; ++i)
c += A[i]&1;
return c<2;
}
bool palindromeRearranging(std::string inputString) {
std::vector<int> cnt(26);
for (auto it : inputString)
cnt[it - 'a']++;
int oddCount = 0;
for (int i = 0; i < 26; ++i)
if (cnt[i] & 1)
oddCount++;
return oddCount < 2;
}
반응형