반응형
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;
}
반응형
'알고리즘 > codefights' 카테고리의 다른 글
20>arrayMaximalAdjacentDifference (0) | 2017.07.04 |
---|---|
19>areEquallyStrong (0) | 2017.07.02 |
17>arrayChange (0) | 2017.07.01 |
16>areSimilar (0) | 2017.06.28 |
15>addBorder (0) | 2017.06.28 |