解题思路
本题要求验证给定的字符串序列是否满足字典序排序和长度排序。我们需要:
- 检查是否按字典序排序
- 检查是否按长度排序
- 根据两种检查的结果确定最终输出
关键点
- 字符串长度都不相同
- 需要同时验证两种排序方式
- 根据验证结果输出四种可能的结果
代码
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string checkOrder(vector<string>& strs) {
bool isLex = true; // 是否满足字典序
bool isLen = true; // 是否满足长度序
// 检查相邻字符串
for (int i = 1; i < strs.size(); i++) {
// 检查字典序
if (strs[i] <= strs[i-1]) {
isLex = false;
}
// 检查长度序
if (strs[i].length() <= strs[i-1].length()) {
isLen = false;
}
}
// 根据检查结果返回结果
if (isLex && isLen) return "both";
if (isLex) return "lexicographically";
if (isLen) return "lengths";
return "none";
}
};
int main() {
int n;
cin >> n;
vector<string> strs(n);
for (int i = 0; i < n; i++) {
cin >> strs[i];
}
Solution solution;
cout << solution.checkOrder(strs) << endl;
return 0;
}
import java.util.Scanner;
public class Main {
static class Solution {
public String checkOrder(String[] strs) {
boolean isLex = true; // 是否满足字典序
boolean isLen = true; // 是否满足长度序
// 检查相邻字符串
for (int i = 1; i < strs.length; i++) {
// 检查字典序
if (strs[i].compareTo(strs[i-1]) <= 0) {
isLex = false;
}
// 检查长度序
if (strs[i].length() <= strs[i-1].length()) {
isLen = false;
}
}
// 根据检查结果返回结果
if (isLex && isLen) return "both";
if (isLex) return "lexicographically";
if (isLen) return "lengths";
return "none";
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine(); // 消耗换行符
String[] strs = new String[n];
for (int i = 0; i < n; i++) {
strs[i] = sc.nextLine();
}
Solution solution = new Solution();
System.out.println(solution.checkOrder(strs));
sc.close();
}
}
class Solution:
def check_order(self, strs: list) -> str:
is_lex = True # 是否满足字典序
is_len = True # 是否满足长度序
# 检查相邻字符串
for i in range(1, len(strs)):
# 检查字典序
if strs[i] <= strs[i-1]:
is_lex = False
# 检查长度序
if len(strs[i]) <= len(strs[i-1]):
is_len = False
# 根据检查结果返回结果
if is_lex and is_len:
return "both"
if is_lex:
return "lexicographically"
if is_len:
return "lengths"
return "none"
def main():
n = int(input())
strs = [input() for _ in range(n)]
solution = Solution()
print(solution.check_order(strs))
if __name__ == "__main__":
main()
算法及复杂度
- 算法:线性扫描
- 时间复杂度:,其中 是字符串个数
- 空间复杂度:,只使用了常数额外空间