/*
*时间:2018年4月30日21:41:49-2018年4月30日22:35:54
*题目:1077.Kuchiguse
*分数:20
*编译器:g++
*题目描述:
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
*/
//思路:这题题目看起来还是比较有意思的,其实是算一个最大后缀。用第一个字符串去匹配所有的字符串。主要有几个难点:
//1、输入为带空格的char类型的数组,还要注意下cin之后有个回车需要用getchar();去掉,然后每个char类型的数组用gets(a[i]);就可以啦
//2、要记录一个最小的长度,不然会超出一个长度继续匹配,可能会匹配到'\0',而且容易超时
//3、将数组反过来再匹配前缀可以防止超时,而且会变得简单一些
//4、自己的一些小的不好的习惯会产生一些很难查找的错误,比如第五个点应该是最短的那个字符全部匹配上了,就不能再break的时候输出sameLenth = i;
#include <iostream>
using namespace std;
#include <string.h>
#include <stdio.h>
int main()
{
int N;
cin>>N;
char a[N][256];
int minLen = 256;
getchar();//去掉cin后面的'\n',很容易忽略
for (int i=0; i<N; i++)
{
gets(a[i]);
if (strlen(a[i]) < minLen) minLen = strlen(a[i]);//得到一个最小字符串的长度
for (int j=0; j<strlen(a[i])/2; j++)//反转数组
{
char temp = a[i][j];
a[i][j] = a[i][strlen(a[i])-j-1];
a[i][strlen(a[i])-j-1] = temp;
}
}
int sameLenth = 0;
bool flag = false;//是否有没有匹配上的,置位true
for (int i=0; i<minLen; i++)
{
char ch = a[0][i];//用第一个字符串的字符来匹配所有的字符串
for (int j=1; j<N; j++)
{
if (ch != a[j][i])//没有匹配上的情况
{
flag = true;
break;
}
}
if (flag) break; //没匹配上就break
sameLenth++; //原来我写的是在break的时候赋值sameLenth = i;其实有可能会flag一直都是false i.e.最短的字符串全部匹配上啦
}
if (sameLenth == 0) cout<<"nai"<<endl;//匹配个数为0的情况
else for (int i=sameLenth-1; i>=0; i--) cout<<a[0][i];
return 0;
}
【PAT甲】A1077
最新推荐文章于 2020-03-14 13:58:58 发布