寻找最长共同后缀,由于位置固定,难度较小;
A 1077
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(2<=N<100)个有可能包含空格的字符串(长度小于等于256),找出它们的共同后缀并输出,如果没有共同后缀,则输出nai。
思路
- 使用c风格字符数组读入字符串
编写一个字符串反转函数,使所有输入的字符串反转,实现后缀的对齐
//字符串反转函数 void Reverse(char s[], int n) { for (int i = 0, j = n - 1; i < j; i++, j--) { char temp = s[i]; s[i] = s[j]; s[j] = temp; } }
假设输入的第一个字符串是共同后缀
subStr
- 将接下来输入的字符串与
subStr
逐个字符比较,如果第i个字符不相同,则令subStr[i] = '\0'
,相当于截短了子串 - 如果
subStr[0]
为'\0'
,说明没有共同后缀,输出nai,否则输出subStr
AC代码
#include <iostream>
#include <cstdio>
#include <stdlib.h>
#include <string.h>
using namespace std;
void Reverse(char s[], int n) {
for (int i = 0, j = n - 1; i < j; i++, j--) {
char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
int main() {
int N;
cin >> N;
cin.get(); // 抛掉cin流中的'\n'
char subStr[257];
for (int i = 0; i < N; i++) {
char temp[257];
cin.getline(temp, 257); // 因为输入字符中可能有空格 所以要用getline
Reverse(temp, strlen(temp));
if (i == 0) {
strcpy(subStr, temp);
}
else {
for (int j = 0; j < 257 && subStr[j] != '\0'; j++) {
if (temp[j] != subStr[j]) {
subStr[j] = '\0';
break;
}
}
}
}
Reverse(subStr,strlen(subStr));
if (subStr[0] == '\0') {
cout << "nai";
}
else {
cout << subStr;
}
return 0;
}