题意:
给n个字符串,要求按照长度排序后,若每个前面的字符串是后面的子串,输出“YES”,并输出结果,否则输出“NO”
Input
5 a aba abacaba ba aba
Output
YES a ba aba aba abacaba
Input
5 a abacaba ba aba abab
Output
NO
Input
3 qwerty qwerty qwerty
Output
YES qwerty qwerty qwerty
这个题对我来说有两个难点,一个是用sort按长度排序字符串数组,另一个是substr的使用。
这里只说一下substr吧:substr是字符串截取函数,头文件是string。
用法:substr(截取的起始位置,截取的长度);
代码:
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 200;
typedef long long ll;
int n;
string s[maxn];
bool cmp(string &a,string &b)//按字符串长度排序
{
return a.size() < b.size();
}
bool check(int i, int m,int t)
{
int flag = 1;
for (int j = 0; j <= m-t; j++) {
if (s[i].substr(j, t) == s[i-1])
return true;
else flag = 0;
}
if (flag == 0)
return false;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
for (int i = 0; i < n; i++)
cin >> s[i];
sort(s, s + n, cmp);
for (int i = 1; i < n; i++) {
int t = s[i-1].size();
int m = s[i].size();
if (check(i, m,t) == false) {
cout << "NO" << endl;
return 0;
}
}
cout << "YES" << endl;
for (int i = 0; i < n; i++) {
cout << s[i] << endl;
}
return 0;
}