题解 | #两种排序方法#
两种排序方法
https://www.nowcoder.com/practice/839f681bf36c486fbcc5fcb977ffe432
思路:定义两个标志位lexicographically、lengths记录是否满足这两种情况
只需保存两个字符串遍变量,一个prev_str字符串,一个当前cur_str字符串,判断是否满足这两个条件
1.当lengths 成立时才有必要判断字符串长度
2.当lexicographically成立时才有必要判断字典排序
3.当两个标志位都不成立,终止判断直接输出
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
string prev_str("");
int prev_len = 0;
bool lexicographically = true;
bool lengths = true;
for(int i = 1;i<=n && (lexicographically || lengths);i++)
{
string cur_string;
cin >> cur_string;
int cur_len = cur_string.size();
if(lengths)
{
if(cur_len < prev_len)
{
lengths = false;
}
}
if(lexicographically)
{
if(cur_string < prev_str)
{
lexicographically = false;
}
}
prev_len = cur_len;
prev_str = cur_string;
}
if(lengths && lexicographically)
{
cout << "both" << endl;
}
else if(lengths)
{
cout << "lengths" << endl;
}
else if(lexicographically)
{
cout << "lexicographically" << endl;
}
else
{
cout << "none" << endl;
}
}
网易游戏公司福利 555人发布