
本文介绍如何判断 `list>` 中的子列表是否从左到右严格满足字典序升序(即每个子列表都小于其后一个),支持变长列表和逐索引比较,避免越界异常。
要验证一个 List ✅ 正确策略是:为 List Java 中 List 的自然字典序已由 Collections.compare()(Java 9+)或手动迭代器实现支持。以下是一个清晰、健壮、无异常风险的实现: 判断嵌套整数列表是否严格字典序升序,本质是复用标准字典序逻辑:先比同位置元素,元素相等则短者更小。通过一个健壮的 Comparator> 是否按严格字典序升序排列(即 list[0]
✅ 推荐实现:基于标准字典序比较器
import java.util.*;
public class LexicographicListChecker {
// 核心:定义 List<Integer> 的字典序升序比较器(严格升序)
public static final Comparator<List<Integer>> LEXICOGRAPHIC_INTEGER_LIST_COMPARATOR =
(list1, list2) -> {
Iterator<Integer> it1 = list1.iterator();
Iterator<Integer> it2 = list2.iterator();
while (it1.hasNext() && it2.hasNext()) {
Integer v1 = it1.next();
Integer v2 = it2.next();
int cmp = Integer.compare(v1, v2);
if (cmp != 0) return cmp;
}
// 短者在前 → 更小(如 [1,2] < [1,2,3])
if (it1.hasNext()) return 1; // list1 更长 ⇒ list1 > list2
if (it2.hasNext()) return -1; // list2 更长 ⇒ list1 < list2
return 0; // 相等
};
/**
* 判断 listOfLists 是否严格按字典序升序排列(每项 < 下一项)
* @param listOfLists 非 null,允许空列表或含 null 元素(需提前校验)
* @return true 当且仅当所有相邻对满足 list[i] < list[i+1]
*/
public static boolean isStrictlyLexSorted(List<List<Integer>> listOfLists) {
if (listOfLists == null || listOfLists.size() <= 1) {
return true;
}
for (int i = 0; i < listOfLists.size() - 1; i++) {
List<Integer> curr = listOfLists.get(i);
List<Integer> next = listOfLists.get(i + 1);
if (LEXICOGRAPHIC_INTEGER_LIST_COMPARATOR.compare(curr, next) >= 0) {
return false; // 不满足严格升序(相等或逆序均失败)
}
}
return true;
}
// 测试用例
public static void main(String[] args) {
// ✅ 正确顺序:[4,3] < [4,3,1] < [5,4,3] < [5,4,3] ❌ 最后两个相等 → 应返回 false
System.out.println(isStrictlyLexSorted(List.of(
List.of(4, 3),
List.of(4, 3, 1),
List.of(5, 4, 3),
List.of(5, 4, 3)
))); // → false(因最后两列表相等)
// ✅ 严格递增:[3,2,1] < [4,3,1] < [5,4,3]
System.out.println(isStrictlyLexSorted(List.of(
List.of(3, 2, 1),
List.of(4, 3, 1),
List.of(5, 4, 3)
))); // → true
// ❌ 非法:[5,3,2] 与 [5,3] —— 前者更长,故更大,但位置在前 → 违反升序
System.out.println(isStrictlyLexSorted(List.of(
List.of(5, 3, 2),
List.of(5, 3),
List.of(5, 3)
))); // → false
// ❌ 非法:[4,3,2] 在 [4,3,2,1] 之前 → 错误(前者应排后)
System.out.println(isStrictlyLexSorted(List.of(
List.of(4, 3, 2),
List.of(4, 3, 2, 1),
List.of(4, 3, 2, 1)
))); // → false(第二项 > 第一项 ✓,但第三项 == 第二项 ✗)
}
}⚠️ 注意事项与常见误区
✅ 总结
> 封装该逻辑,并在线性扫描中校验每一对相邻列表,即可安全、高效、准确地完成判定——无需栈、无需递归、无需异常捕获,代码简洁且语义清晰。










