[PTA] A1077 [字符串处理]Kuchiguse (20 分)

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个字符串,求最长公共后缀,不存在的话输出nai

思路

看到后就想到前,将所有的字符串逆序,则问题变为最长前缀,这时候居然跟上了柳神的思路(笑)

令第一个字符串为ans,和接下来的字符串逐个对比,敲掉不一样的

新の函数:substr

// string::substr
#include <iostream>
#include <string>

int main ()
{
  std::string str="We think in generalities, but we live in details.";
                                           // (quoting Alfred N. Whitehead)

  std::string str2 = str.substr (3,5);     // "think"

  std::size_t pos = str.find("live");      // position of "live" in str

  std::string str3 = str.substr (pos);     // get from "live" to the end

  std::cout << str2 << ' ' << str3 << '\n';

  return 0;
}
think live in details.

踩坑

cin.ignore();

为啥要加这一句呢

”是cin流在读取数据之后会把回车符之前的字符拿去传递给buf然后将回车符残留在cin流中,所以当getline在读取cin流的时候会第一个读到回车符随之而退出 “

可以在getline之前使用cin.ignore()函数来将cin的残留回车符清除。

实现

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;


int main() {
    int n;
    cin >> n;
    cin.ignore();
    string s;
    getline(cin, s);
    string ans = s;
    reverse(ans.begin(), ans.end());
    for (int i = 1; i < n; i++)
    {
        getline(cin, s);
        reverse(s.begin(), s.end());
        int len = min(ans.length(), s.length());
        for (int j = 0; j < len; j++)
        {
            if (ans[j]!=s[j])
            {
                ans = ans.substr(0, j);
                break;
            }
        }
    }
    if (ans.length() == 0)
    {
        ans = "nai";
    }
    else
    {
        reverse(ans.begin(), ans.end());
    }
    cout << ans;

    return 0;

}

发表评论