解题思路和代码:
/*************************************************************************
> File Name: URL.cpp
> Author: 念念
> Mail: 2845906049@qq.com
> Created Time: 2021年08月26日 星期四 19时48分09秒
> Function: 给定一个字符串,编写一个函数判定其是否为某个回文串的排列之一。
回文串是指正反两个方向都一样的单词或短语。排列是指字母的重新排列。
回文串不一定是字典当中的单词。
************************************************************************/
#include <iostream>
#include <string>
using namespace std;
//判断是否为回文串(一开始理解错题了)
bool isPalindrome(string s)
{
int i = 0;
int j = s.length() - 1;
while(i < j)
{
if(s[i++] != s[j--])return false;
}
return true;
}
//判断是否是某个回文的排列之一
//思路:最多只能有一个字符的数目是奇数个
//效果: 100% 72.24%
bool canPalindrome(string s)
{
short asc[128] = {0};
for(auto c : s) //范围for循环,记录每个字符的数目
{
++asc[c];
}
int count = 0; //记录数目为奇数的字符个数
for(int num : asc)
{
if(num % 2 == 1)count++;
if(count >= 2)return false;
}
return true;
}
int main()
{
cout << isPalindrome("tactcoa") << endl;
cout << canPalindrome("tactcoa") << endl;
return 0;
}