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?
输入描述:
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.
输出描述:
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".
输入例子:
3 Itai nyan~ Ninjin wa iyadanyan~uhhh nyan~
这道题坑爹的就在于,是不是真的看懂了题目。我第一次,很费劲的读了好几遍,没太看懂,好像是说日本话会在句尾加一个缀词,显示人物性格。但是这和题目有什么关系呢?后来再百度翻译也没看懂,猜想应该是字符串之间的比较吧,就想到了strcmp(),但是其实这道题和这个没太大关系。参考了大神们的博客,终于理解了一下意思,总之归位两种情况:
输出为"nai"的时候,是在n行输入的字符里,只要有一行最后的字符串(倒着数,不管多长,只要大于等于1),和其他所有行的,结尾,都没有公共字符串(必须严格从最后一个字符开始倒着数),即没有任何吻合的情况,就直接nai了,全部结束。
不然,我们就输出所有行(严格按照顺序,倒着数),大家公共的部分,即大家都有的部分。
#include<iostream> #include<string> using namespace std; int main() { string kuru; string s; int n; cin >> n; getchar(); getline(cin, kuru); //getchar(); for (int i = 1; i < n; i++) { int j = 0; getline(cin, s); while (kuru[kuru.size() - j - 1] == s[s.size() - j - 1]) { j++; if (j == s.size() || j == kuru.size()) { break; } } if (j == 0) { cout << "nai" << endl; return 0; } string ss; ss.assign(kuru, kuru.size() - j, j); kuru = ss; } cout << kuru << endl; return 0; }