其他分享
首页 > 其他分享> > PAT-A1077 Kuchiguse

PAT-A1077 Kuchiguse

作者:互联网

A1077 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:

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行字符串,寻找它们共同的后缀,如果存在共同的后缀,就输出共同的后缀;如果不存在,就输出nai

分析:

  1. 接收数值,注意换行符,数值类型,空格
  2. 寻找最小长度(为了之后的遍历),数组反转
  3. 遍历查找相同字符串,从in [0] [1] 到in [0] [minlen];如果不相等就直接结束循环,否则计时器count+1,继续遍历in [i] [i]…
  4. 如果计时器count=0,说明没有公共后缀,输出nai; 否则就遍历倒序输出公共后缀

注意点:

代码如下:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
string in[256];//接收数据
int main(){
	int n,count=0;
	int minlen=256;
	scanf("%d",&n);
	getchar();//接收换行符 
	for(int i=0;i<n;i++){
	    //scanf("%s",&in[i]);因为有空格,不能能用scanf来接收
         getline(cin, in[i]);
        int len=in[i].size();
		if(len<minlen) minlen=len;
		//数组翻转
     	reverse(in[i].begin(),in[i].end()); //注意!!! 
	}
	
	//寻找相同
	int i,j;
	bool flag;
	for(i=0;i<minlen;i++){
		flag=true;
		for(j=1;j<n;j++){
			if(in[0][i]!=in[j][i]){
				flag=false;
				break;
			}
		}
		if(flag) count++;//字符串第i位相等,计时器count+1 
		else break;	
    }
	if(count==0) printf("nai");
	else{
		for(i=count-1;i>=0;i--){
			printf("%c",in[0][i]);
		}
	}	 
	return 0;
} 

标签:case,nyan,include,PAT,后缀,int,Kuchiguse,A1077
来源: https://blog.csdn.net/weixin_46055626/article/details/120373014