对称之美
题目描述
给出n个字符串,从第1个字符串一直到第n个字符串每个串取一个字母来构成一个新字符串,新字符串的第i个字母只能从第i行的字符串中选出,这样就得到了一个新的长度为n的字符串,请问这个字符串是否有可能为回文字符串?
输入描述:
第一行一个数字 t , 1 ≤ t ≤ 50 1\le t \le50 1≤t≤50,代表测试数据的组数
每组测试数据先给出一个数字 n,然后接下来n行每行一个只由小写字母组成的字符串 s i s_i si
1 ≤ n ≤ 100 1 \le n \le 100 1≤n≤100, 1 ≤ ∣ s i ∣ ≤ 50 1\le |s_i| \le50 1≤∣si∣≤50
输出描述:
在一行中输出 “Yes” or “No”
示例1
输入
2
1
a
3
a
b
c
输出
Yes
No
解题思路分析
对于字符串i来说,只要字符串i中的某个字母在第n - i - 1个字符串中出现,则当前即满足对称的关系,继续去判断第i + 1个字符串;如果第i个字符串中的所有字母在第n - i - 1个字符串中都没出现过,则可以判断是不满足的,因为无法满足i和n - i - 1对称相等。
#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<cstring>
#include<unordered_map>
#include<numeric>
using namespace std;
int main()
{
int T; cin >> T;
while(T--){
int n; cin >> n;
vector<string> v(n);
for(int i = 0; i < n; i++) cin >> v[i];
bool flag = false;
if(n == 1) puts("Yes");
else{
for(int i = 0; i < (n >> 1); i++){
for(int j = 0; j < v[i].size(); j++){
char ch = v[i][j];
//cout << "ch: " << ch << endl;
if(v[n - i - 1].find(ch) != string::npos) {
flag = true;
break;
}else{
flag = false;
}
}
if(flag == false) break;
}
}
if(flag) puts("Yes");
else puts("No");
}
return 0;
}
博客围绕算法题展开,题目是从n个字符串中各取一个字母构成新字符串,判断其是否为回文。给出输入输出描述及示例,解题思路为判断字符串i中是否有字母在第n - i - 1个字符串出现,若有则继续判断下一个,否则不满足对称。

被折叠的 条评论
为什么被折叠?



