PAT-字符串处理-A 1077 Kuchiguse (20分)

题目:

思路:

  读入字符串,并将字符串翻转后,存储到向量中,设置计数器,并以第一个字符串,为比较字符串,遍历向量中的字符串,对字符串从头到尾进行比较,记录公共字母,不相等时跳出循环

输出结果

注意点:

  使用getline读取一行时,首先要对getchar或者其他输入语句读取换行符,确保getline读取正常

代码:

 1 #include<iostream>
 2 #include<string>
 3 #include<vector>
 4 #include<algorithm>
 5 using namespace std;
 6 
 7 int main()
 8 {
 9     int num, count = 0;
10     bool flag = true;
11     string res = "", temp;
12     vector<string> lines;
13 
14     cin >> num;
15     getchar();
16 
17     //读取字符串并将字符串翻转存储
18     for (int i = 0;i < num;i++)
19     {
20         getline(cin, temp);
21         
22         reverse(temp.begin(), temp.end());
23         lines.push_back(temp);
24     }
25 
26     //获取公共部分
27     while(flag && count<lines[0].size())
28     {
29         for (int i = 0;i < num;i++)
30         {
31             //不相等时跳出整个循环
32             if (lines[i][count] != lines[0][count])flag = false;
33         }
34 
35         if (!flag)break;
36         res = lines[0][count] + res;
37         count++;
38     }
39 
40     //依据公共部分的结果进行输出
41     if (res.size() > 0)cout << res;
42     else cout << "nai";
43 
44     return 0;
45 }
View Code
原文地址:https://www.cnblogs.com/fangzhiyou/p/12495483.html