PAT 甲 1077 Kuchiguse

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
思路:
将输入的字符串先反转,从前往后比较方便,先去第一个字符串的全部,然后和第二个字符串比较,利用substr()截止到不相同的字符处作为新的字符串,然后在与后面字符串比较
因为可能含有空格,所以用getline读入,此时注意用getchar吸收cin>>n后面换行符
C++代码:

#include<cstdio>
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main(){
	int n;
	cin>>n;
	getchar();
	string str;
	for(int i=0;i<n;i++){
		string s1;
		getline(cin,s1);
		int lens=s1.length();
		reverse(s1.begin(),s1.end());
		if(i==0){
			str=s1;
			continue;
		}
		else{
			int len1=str.length();
			int minlen=min(lens,len1);
			int j=0,count=0;
			while(str[j]==s1[j]&&j<minlen){
				j++;
				count++;
			} 
			str=str.substr(0,count);

		}
	}
	reverse(str.begin(),str.end());
	if(str.length()==0){
		cout<<"nai"<<endl;
	}
	else{
			cout<<str;
	}
	return 0;
}
发布了65 篇原创文章 · 获赞 5 · 访问量 4145

猜你喜欢

转载自blog.csdn.net/u014424618/article/details/105060667
今日推荐