题目描述:
解题思路:
代码实现:
#include <iostream>
#include <stack>
#include <vector>
#include <string>
#include <map>
#include <unordered_map>
using namespace std;
bool RecursionSolution(const string &s, int i, int j) {
if (i >= j) {
return true;
}
if (s[i] != s[j]) {
return false;
}
return s[i] == s[j] && RecursionSolution(s, i + 1, j - 1);
}
bool NoRecursionSolution(const string s) {
int n = s.length();
for (int i = 0; i < n / 2; i++) {
if (s[i] != s[n - 1 - i]) {
return false;
}
}
return true;
}
void RemoveSpace(string &s) {
string res = "";
for (auto c: s) {
if (c != ' ') {
res += c;
}
}
s = res;
return;
}
void ToUpper(string &s) {
for (auto & c: s) {
if (islower(c)) {
c ^= 32;
}
}
}
void TestCase() {
using psb = pair<string, bool>;
vector<psb> t = {
{"123321", true},
{" 12 3 4 3 21", true},
{"abcAbc", true},
{"abcCbA", true},
{"aaccbbdd", false}
};
bool flag = false;
for (auto& x : t) {
RemoveSpace(x.first);
ToUpper(x.first);
if (RecursionSolution(x.first, 0, x.first.length() - 1) != x.second || NoRecursionSolution(x.first) != x.second) {
flag = true;
}
}
if (flag) {
cout << "error" << endl;
} else {
cout << "all accept" << endl;
}
}
int main() {
cout << "please input str:" << endl;
string s;
getline(cin, s);
RemoveSpace(s);
cout << s << endl;
cout << "case 1 recursion solution" << endl;
if (RecursionSolution(s, 0, s.length() - 1)) {
cout << "yes" << endl;
} else {
cout << "no" << endl;
}
cout << "case 2 no recursion solution" << endl;
if (NoRecursionSolution(s)) {
cout << "yes" << endl;
} else {
cout << "no" << endl;
}
TestCase();
return 0;
}