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。


解题思路:先读入n,然后保存第一串字符串,与之后的n-1串字符串相比较,找到每行中相同的后缀。怎么找呢?比较两个字符串长度,取字符串长度较小的进行for循环,保证字符数组不会越界,两个字符串同时从末尾开始比较。这样就可以得到他们的公共后缀长度啦,当有一组公共后缀长度为0,用flag标记一下,最后输出结果就行。


#include<bits/stdc++.h>
using namespace std;
int main()
{
	int n, l, l1, l2, common;
	bool flag = true;
	scanf("%d", &n);
	getchar();
	string s, tmp;
	for(int i=0; i<n; i++){
		getline(cin,tmp);
		if(i==0){
			s = tmp;
			l1 = s.length();
			common = l1;
			continue;
		}
		l2 = tmp.length();
		l = min(l1,l2);
		int count = 0;
		for(int j=1; j<=l; j++){
			if(tmp[l2-j]==s[l1-j]){
				count++;
			}
			else break;
		}
		if(count==0){
			flag = false;
		}
		common = min(common,count);
	}
	if(flag){
		string ans = s.substr(l1-common);
		cout << ans << endl;
	}
	else printf("nai\n");
	return 0;
}