题目:
考拉最近学习到有两种字符串的排序方法:
1.根据字符串的字典序排序。例如:
“car” < “carriage” < “cats” < “doggies < “koala”
2.根据字符串的长度排序。例如:
“car” < “cats” < “koala” < “doggies” < “carriage”
考拉想知道自己的这些字符串排列顺序是否满足这两种排序方法,考拉要忙着吃树叶,所以需要你来帮忙验证。
输入描述:
输入第一行为字符串个数n(n ≤ 100)
接下来的n行,每行一个字符串,字符串长度均小于100,均由小写字母组成
输出描述:
如果这些字符串是根据字典序排列而不是根据长度排列输出”lexicographically”,
如果根据长度排列而不是字典序排列输出”lengths”,
如果两种方式都符合输出”both”,否则输出”none”
输入例子:
3
a
aa
bbb
输出例子:
both
答案:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool isLexicographically(vector<string>strings, int index){
if (index == strings.size()-1) {
return true;
}
int com = strings[index].compare(strings[index+1]);
if (com < 0) {
return isLexicographically(strings,index+1);
}else{
return false;
}
return false;
}
bool isLengths(vector<string>strings, int index){
if (index == strings.size()-1) {
return true;
}
int com = int(strings[index].length() - strings[index+1].length());
if (com < 0) {
return isLengths(strings,index+1);
}else{
return false;
}
return false;
}
int main(){
int n;
cin>>n;
vector<string> vector;
string s;
while (n--) {
cin>>s;
vector.push_back(s);
}
bool a = isLexicographically(vector, 0);
bool b = isLengths(vector, 0);
if (a && b) {
cout<<"both"<<endl;
}else if (a){
cout<<"lexicographically"<<endl;
}else if (b){
cout<<"lengths"<<endl;
}else {
cout<<"none"<<endl;
}
return 0;
}