1.题目描述
链接:https://www.nowcoder.com/questionTerminal/839f681bf36c486fbcc5fcb977ffe432
考拉有n个字符串字符串,任意两个字符串长度都是不同的。考拉最近学习到有两种字符串的排序方法:
1.根据字符串的字典序排序。例如:** “car” < “carriage” < “cats” < "doggies < “koala”
2.根据字符串的长度排序。例如: “car” < “cats” < “koala” < “doggies” < “carriage” 考拉想知道自己的这些字符串排列顺序是否满足这两种排序方法,考拉要忙着吃树叶,所以需要你来帮忙验证。 输入描述: 输入第一行为字符串个数n(n
≤ 100) 接下来的n行,每行一个字符串,字符串长度均小于100,均由小写字母组成输出描述: 如果这些字符串是根据字典序排列而不是根据长度排列输出"lexicographically",
如果根据长度排列而不是字典序排列输出"lengths",
如果两种方式都符合输出"both",否则输出"none"
2.思路解析
- 定义两个标记,之后选择输出的字符串
- 先输入一个n,然后string[n + 1]
- 循环开始输入字符串
- 下来进行两种方式的比较
- 最后判断len和dict的值,输出最后的字符串
3.代码实现
#include <iostream>
#include <string>
using namespace std;
int main()
{
int dict = 1;
int len = 1;
int n = 0;
cin >> n;
string str[n + 1];
for(int i = 0; i < n; i++)
{
cin >> str[i];
if(i > 0)
{
if(str[i - 1] > str[i])
dict = 0; // 判断字典
if(str[i - 1].size() > str[i].size())
len = 0; // 判断长度
}
}
if(len == 1 && dict == 1)
cout<<"both"<<endl;
else if(len == 1 && dict == 0)
cout<<"lengths"<<endl;
else if(len == 0 && dict ==1)
cout<<"lexicographically"<<endl;
else
cout<<"none"<<endl;
return 0;
}