查找可能的前缀回文
Finding possible prefix palindromes
我们得到一个长度为 N 的字符串 S。我们必须计算可以重新排列成回文的前缀的数量。例如:考虑字符串"abba"-"a","abb"和"abba"是可以重新排列成回文的前缀。
我的方法:我尝试使用XOR来解决这个问题。例如,如果字符串中所有字符的异或 0.In 则包含偶数个字符的字符串可以成为回文 对于具有奇数字符的字符串,所有字符的异或应介于 97 和 122 之间,即单个字符。
这是我代码的一部分-
string s;
cin>>s;
int a,n;
int ans=1;
n= s.length();
a=s[0];
for (int i=1;i<n;i++)
{
a=a^(s[i]);
if (i%2)
{
if (a==0)
{
ans++;
}
}
else
{
if ((a>=97)&&(a<=122))
{
ans++;
}
}
}
cout<< ans<< "n";
我尝试运行,它在某些测试用例中成功运行,但在其他测试用例中失败。知道这种方法有什么问题吗?
更好的解决方案,基于OP的评论:
#include <string>
#include <iostream>
#include <cctype>
int main() {
std::string input;
std::cin >> input;
unsigned char_xor = input[ 0 ];
unsigned pal = 1; // number of palindromes (initialized to 1,
// since a singular letter is always a
// palindrome)
for ( std::string::size_type i = 0; input.size() >= i; ++i ) {
char_xor ^= input[ i + 1 ];
// check whether length of current prefix is:
// - odd: check whether it is a lowercase character
// - even: check whether it is equal to 0
if ( ( i % 2 && std::islower( char_xor ) ) ||
( !( i % 2 ) && !char_xor ) ) {
++pal;
}
}
std::cout << "Amount of possible palindromes: " << pal << std::endl;
return 0;
}
以下假设不正确(请参阅下面的注释(。
正如从中了解到的那样
如果字符串中所有字符的异或 0.In,则包含偶数个字符的字符串可以设为回文 对于具有奇数字符的字符串,所有字符的异或应介于 97 和 122 之间
您在每次迭代(XOR
每个字符后(检查计算XOR
是否等于 0/介于 97 和 122 之间时犯了一个错误,而您应该在整个std::string
迭代后检查它。下面与您给出的"abba"示例一起使用,例如"aaaadcasdasdaffaaa"(已产生 12 个(:
#include <string>
#include <iostream>
#include <cctype>
bool can_be_palindrome( const std::string& str ) {
unsigned char_xor = str[ 0 ];
// compute the xor of all characters
for ( std::string::size_type i = 1; str.size() != i; ++i ) {
char_xor ^= str[ i ];
}
// determine whether the input string has an even number of characters;
// if so, return whether char_xor is equal to 0;
// if not, return whether char_xor is a lowercase letter.
return !( str.size() % 2 ) ? !char_xor : std::islower( char_xor );
}
int main() {
std::string input;
std::cin >> input;
unsigned pal = 1; // number of palindromes (initialized to 1, since a
// singular letter is always a palindrome)
for ( std::string::size_type i = 2; input.size() >= i; ++i ) {
// extract a prefix from the range [0; i) and determine whether it
// can become a palindrome
if ( can_be_palindrome( input.substr( 0, i ) ) ) {
++pal;
}
}
std::cout << "Amount of possible palindromes: " << pal << std::endl;
return 0;
}
相关文章:
- C++:正在检查LinkedList中的回文-递归方法-错误
- Usaco第1.6节主要回文
- 最大的回文产品 - 程序未运行,编写解决方案但无法理解问题
- 将 S1 转换为回文,并将 S2 作为其子字符串
- 数回文词
- 最长的回文子串(C++帮助)
- 有人可以详细解释这个回文代码是如何工作的吗?
- 回文递归版本
- 如何检查C ++ STL列表是否为回文?
- 回文数在 1 到 10000 之间
- C++ - 检查结构数据类型中的单词是否为回文
- 是回文作业练习
- 回文递归不停止
- 整数数组中最长的回文
- 回文测试
- 最大的回文产品(Project Euler)——C++
- C++ 回文程序总是给出 0(假)作为输出问题;我的代码哪里有问题?
- 递归回文问题的时间复杂度,C++
- 程序以查找给定字符串中回文的子字符串的数量
- 查找可能的前缀回文