1. 程式人生 > 其它 >字串型別的"Sun Oct 24 20:49:20 CST 2021"轉換為Date格式

字串型別的"Sun Oct 24 20:49:20 CST 2021"轉換為Date格式

1. 題目

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

2. 題意

找出n個語句中的習慣語。習慣語即每句話結尾都要加上的相同語句。

例:

1111111hello

22hello

33333333333hello

那麼這三句話的習慣語為hello。即題目要求找出n句話結尾最長的習慣語,如果沒有則輸出nai

3. 思路——字串

從每句話的末尾遍歷,首先記錄下第一句話倒數第k個字母,然後與其他幾句話的倒數第k個字母進行比較,如果都一致,則將該字母加入結果字串(即習慣語)。直到出現n句話的倒數第k個字母不一致的情況,查詢完畢!其中注意一個細節條件,倒數第k個字母可能對於某句話來說越界了,這時候也要終止查詢。

4. 程式碼

#include <iostream>
#include <string>

using namespace std;

int main()
{
	int n;
	cin >> n;
	string strs[n];
	getchar();
	for (int i = 0; i < n; ++i)
		getline(cin, strs[i]);
		
	int k = 1;
	string res = ""; 
	int flag = 1;		// 終止迴圈條件 
	char ch;
	while (true)
	{ 
		for (int i = 0; i < n; ++i)
		{
			// 判斷每個語句的倒數第k個字母是否相同 
			int j = strs[i].length() - k;
			if (j < 0)	// 越界情況,flag置為0,查詢完畢 
			{
				flag = 0;
				break;
			} 
			// 如果i等於0,表示第一個語句,將該字元記錄下來,與其他語句對比 
			else if (i == 0)
				ch = strs[i][j];
			// 如果對比結果不一致,說明習慣語收集完畢,退出迴圈 
			else if (strs[i][j] != ch) 
			{
				flag = 0;
				break;
			}
		}
		if (!flag) break;
		// 因為ch為倒數第k個字元,所以使用ch+res,這樣可以按原字串順序輸出 
		res = ch + res;
		k++;
	}
	if (res != "")
		cout << res << endl;
	else
		cout << "nai" << endl;
	return 0;
}