1. 验证回文串
题目描述
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: “A man, a plan, a canal: Panama”
输出: true
https://leetcode-cn.com/problems/valid-palindrome/
题目分析
将小写字母全部转换成大写字母,设置头尾指针,分别从前往后 和 从后往前进行遍历,如果遇到非字母则不变 继续往下遍历,直至两个指针分别指向字母,进行对比,不一样返回错误,一样则继续往下寻找。
C++代码
class Solution {
public:
bool isPalindrome(string s) {
for (auto& ch : s)
{
if (ch >= 'a'&&ch <= 'z')
{
ch -= 32;
}
}
int begin = 0;
int end = s.size() - 1;
while (begin < end)
{
while (begin < end && !isalnum(s[begin]))
begin++;
while (begin < end && !isalnum(s[end]))
end--;
if (s[begin] != s[end])
{
return false;
}
else
{
begin++;
end--;
}
}
return true;
}
};
2. 统计回文
题目描述
回文串”是一个正读和反读都一样的字符串,比如“level”或者“noon”等等就是回文串。花花非常喜欢这种拥有对称美的回文串,生日的时候她得到两个礼物分别是字符串A和字符串B。现在她非常好奇有没有办法将字符串B插入字符串A使产生的字符串是一个回文串。你接受花花的请求,帮助她寻找有多少种插入办法可以使新串是一个回文串。如果字符串B插入的位置不同就考虑为不一样的办法。
例如:
A = “aba”,B = “b”。这里有4种把B插入A的办法:
- 在A的第一个字母之前: “baba” 不是回文
- 在第一个字母‘a’之后: “abba” 是回文
- 在字母‘b’之后: “abba” 是回文
- 在第二个字母’a’之后 “abab” 不是回文
所以满足条件的答案为2
题目分析
本题使用暴力求解方式计算即可,遍历str1,将str2 insert进入str1的每个位置,判断是否是回文,是就
++count;需要注意的是这里不能 str1.insert(i, str2),这样的话str1改变了,判断下一个位置就不对了。所
以每次使用str1拷贝构造一个str,然后str.insert(i, str2),再判断。
C++代码
#include<iostream>
#include<string>
using namespace std;
bool IsCircleText(const string& s)
{
int a = 0;
int b = s.size() - 1;
while(a < b)
{
if(s[a] == s[b])
{
a++;
b--;
}else{
return false;
}
}
return true;
}
int main()
{
string str1,str2;
getline(cin,str1);
getline(cin,str2);
int count = 0;
for(int i = 0; i <= str1.size(); i++)
{//将字符串2插入到字符串1的每个位置,再判断是否是回文
string str = str1;
str.insert(i, str2);
if(IsCircleText(str))
{
count++;
}
}
cout << count << endl;
return 0;
}