PAT甲级1077 Kuchiguse 字符串匹配

墨蓝 2023-06-14 11:55 74阅读 0赞
题意:

输入n句话,找出每句话中使用的相同的语气词,其实就是n个字符串中匹配最大相同子字符串问题

解题思路

1.读入每一句话,倒序后存入向量数组v
2.从第一个字符开始循环遍历比较每一个字符串相应位置,如果当前位置每一个字符串都相等,存入output字符串变量
3.逆序output字符串,输出,如果output是空表示不存在匹配的子字符串,输出nai

代码
  1. #include<iostream>
  2. #include<string.h>
  3. #include<algorithm>
  4. #include<string>
  5. #include<vector>
  6. using namespace std;
  7. int main()
  8. {
  9. int n,cnt,min=300;
  10. string output="";
  11. vector<string> v;
  12. cin>>n;
  13. getchar();//读取换行
  14. for(int i=0;i<n;i++)//读入每句话
  15. {
  16. string a;
  17. getline(cin,a);
  18. int len=a.size();
  19. if(len<min)min=len;
  20. reverse(a.begin(),a.end());
  21. v.push_back(a);
  22. }
  23. for(cnt=0;cnt<=min;cnt++)//比较的字符下标
  24. {
  25. char cmp=v[0][cnt];
  26. for(int i=1;i<v.size();i++)//每一个字符串
  27. {
  28. if(v[i][cnt]!=cmp)
  29. {
  30. cnt=min+1;
  31. break;
  32. }
  33. }
  34. if(cnt<=min)
  35. output+=cmp;
  36. }
  37. reverse(output.begin(),output.end());
  38. if(output!="")
  39. cout<<output<<endl;
  40. else cout<<"nai"<<endl;
  41. return 0;
  42. }

发表评论

表情:
评论列表 (有 0 条评论,74人围观)

还没有评论,来说两句吧...

相关阅读