题目链接
解题思路
首先将所有行保存到一个字符串数组中,然后遍历除第一个以外的字符串,判断第一个字符串是否从后往前存在,如果不存在就去掉第一个字符串strs[0]的第一个字符,直到字符串中存在,然后再遍历下一个字符串!
注意
1、读取一整行使用getline(cin,str);但是在读取前如果有一个整数n,需要使用getchar();或者getline先把末尾的回车符读掉。
2、判断一个字符串是否在另一个字符串中,不能用find_last_of,这种是判断是否有某个相同的字符的!!!要用find或者rfind!find是从前往后,rfind是从后往前!!!
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| #include <iostream> #include <cstdio> #include <string> using namespace std; const int maxn=110; string strs[maxn]; int main(){ int n; cin>>n; getchar(); for(int i=0;i<n;i++){ getline(cin,strs[i]); } for(int j=1;j<n;j++){ while(strs[j].rfind(strs[0])==string::npos){ strs[0].erase(strs[0].begin()); } } if(strs[0].length()==0) cout<<"nai"; else cout<<strs[0]; return 0; }
|