本文主要是介绍1077 Kuchiguse (20 分) 字符串处理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
The Japanese language is notorious for its sentence ending particles. Personal preference of such particles can be considered as a reflection of the speaker’s personality. Such a preference is called “Kuchiguse” and is often exaggerated artistically in Anime and Manga. For example, the artificial sentence ending particle “nyan~” is often used as a stereotype for characters with a cat-like personality:
Itai nyan~ (It hurts, nyan~)Ninjin wa iyada nyan~ (I hate carrots, nyan~)
Now given a few lines spoken by the same character, can you find her Kuchiguse?
Input Specification:
Each input file contains one test case. For each case, the first line is an integer N (2≤N≤100). Following are N file lines of 0~256 (inclusive) characters in length, each representing a character’s spoken line. The spoken lines are case sensitive.
Output Specification:
For each test case, print in one line the kuchiguse of the character, i.e., the longest common suffix of all N lines. If there is no such suffix, write nai.
Sample Input 1:
3
Itai nyan~
Ninjin wa iyadanyan~
uhhh nyan~
Sample Output 1:
nyan~
Sample Input 2:
3
Itai!
Ninjinnwaiyada T_T
T_T
Sample Output 2:
nai
题意:输入n个字符串,求这n个字符串的公共后缀,如果不存在公共后缀,就输出nai
思路:求公共后缀的话,反过来比较比较麻烦,因此在输入这个字符串的时候就对它进行了reverse处理,当前输入为第一个字符串的时候,就把这个字符串赋值给ans,然后输入第二个字符串的时候同样将这个字符串反转,然后先取ans和第二个字符串的最小长度,然后遍历,如果出现不一样的话,就用substr(0,j)从开始截到不一样的这个字符结束,然后重新保存在ans中,最后所有输入完以后看ans的长度,如果ans的长度等于0的话,就将ans=“nai”,不等于0的话也不用赋值,直接输出。
一个比较坑的地方就是输入n的时候一定要scanf("%d\n"),要有换行标记。
#include<iostream>
#include<cstdio>
#include<stack>
#include<queue>
#include<vector>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
#include<set>
#include<map>using namespace std;int main() {int n;scanf("%d\n",&n);string ans;for(int i = 0;i < n;i++) {string s;getline(cin,s);int length1 = s.length();reverse(s.begin(),s.end());if(i == 0) {ans = s;continue;} else {int length2 = ans.length();int minlength = min(length1,length2);for(int j = 0;j < minlength;j++) {if(s[j] != ans[j]) {ans = ans.substr(0,j);break;}}}}reverse(ans.begin(),ans.end());if(ans.length() == 0) {ans = "nai";} cout << ans << endl;return 0;
}
这篇关于1077 Kuchiguse (20 分) 字符串处理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!