题意
找出一个序列中最长的对称子序列长度
思路分析
暴力枚举对称子序列的两个头尾,i,j。然后判断这两个字符之间的字符串能否构成对称子序列,若能则更新最大的子序列长度。最大输出最大的子序列长度
注意点:
- 输入不能使用cin,scanf,因为输入的字符串中有空白字符(空格),无法得到正确的输入
也不能使用c++的
getline(cin,s)
,否则会出现超时。参考代码
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1010;
char s[maxn];
bool isSymmetric(int from,int to) { //判断是不是对称的字符串,即回文,
int len = to - from + 1; //字符串长度
int count = 0; //循环次数
for(int i = from;i < len/2+from;i++,count++) { //注意此处循环的写法
if(s[i] != s[to-count]) return false;
}
return true;
}
int main(void){
fgets(s,maxn,stdin);
int len = strlen(s) - 1;
int Max = 1;
for(int i = 0;i < len-1;i++) { //枚举字符串的头
for(int j = i+1;j < len;j++) { //枚举尾
if(isSymmetric(i,j) && (j-i+1) > Max) {
Max = (j-i+1);
}
}
}
cout<<Max;
return 0;
}