[英]Rearrange String to Form Palindrome in C
Given a string in C.给定 C 中的字符串。
How can I rearrange the given string so it form a palindrome?如何重新排列给定的字符串以使其形成回文?
Is there a way to implement it in O(n)
time complexity and O(1)
space complexity?有没有办法以O(n)
时间复杂度和O(1)
空间复杂度来实现它?
bool canFormPalindrome(string str)
{
// Create a count array and initialize all
// values as 0
int count[NO_OF_CHARS] = { 0 };
// For each character in input strings,
// increment count in the corresponding
// count array
for (int i = 0; str[i]; i++)
count[str[i]]++;
// Count odd occurring characters
int odd = 0;
for (int i = 0; i < NO_OF_CHARS; i++) {
if (count[i] & 1)
odd++;
if (odd > 1)
return false;
}
// Return true if odd count is 0 or 1,
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.