Java字符串数组最长连续数字序列查找与列表序列统计问题求助
一、Java中查找字符串数组的最长连续数字序列
实现思路
遍历数组时维护两个核心变量:
currentLength:记录当前正在统计的连续数字序列长度maxLength:记录遍历过程中找到的最长序列长度
遇到数字时,currentLength自增;遇到非数字时,将currentLength与maxLength对比更新,随后重置currentLength为0。遍历结束后必须再做一次对比,避免遗漏数组末尾的连续数字序列。
代码示例
public class LongestNumberSequence { public static int findLongestConsecutiveNumbers(String[] arr) { int maxLength = 0; int currentLength = 0; for (String s : arr) { // 匹配正整数,可根据实际需求调整数字判断规则 if (s.matches("\\d+")) { currentLength++; } else { maxLength = Math.max(maxLength, currentLength); currentLength = 0; } } // 处理数组末尾未被触发的连续数字序列 maxLength = Math.max(maxLength, currentLength); return maxLength; } public static void main(String[] args) { String[] test1 = {"4", "15", "9", "I", "30", "2", "I", "20"}; System.out.println(findLongestConsecutiveNumbers(test1)); // 输出3 String[] test2 = {"I", "I", "I"}; System.out.println(findLongestConsecutiveNumbers(test2)); // 输出0 String[] test3 = {"10", "20", "30"}; System.out.println(findLongestConsecutiveNumbers(test3)); // 输出3 } }
二、修复给定代码的问题
原代码核心问题
- 触发条件单一:仅在遇到"I"时才更新最长序列,完全忽略数组末尾的连续数字,全数字场景下无法输出正确结果
- 逻辑冗余混乱:
hasHit变量的设计无意义,反而增加了计算错误的概率
修复后的代码
重新梳理逻辑,直接跟踪当前连续已完成项的长度,覆盖所有场景:
// numItems为输入开头的元素总数,listItems为后续的元素数组 int currentSeq = 0; int longestSeq = 0; for (int i = 0; i < numItems; i++) { if (listItems[i].equals("I")) { // 遇到未完成项,更新最长序列并重置当前计数 longestSeq = Math.max(longestSeq, currentSeq); currentSeq = 0; } else { // 遇到已完成项,当前序列长度加1 currentSeq++; } } // 处理最后一段未被触发的连续已完成项 longestSeq = Math.max(longestSeq, currentSeq); System.out.println(longestSeq);
多场景验证
- 示例输入:
8 4 15 9 I 30 2 I 20→ 输出3(符合预期) - 全数字输入:
3 1 2 3→ 输出3(原代码输出0,修复后正确) - 全"I"输入:
4 I I I I→ 输出0(符合预期) - 末尾为数字输入:
5 1 I 2 3 4→ 输出3(修复后正确捕获最后一段)
内容的提问来源于stack exchange,提问作者Ashley
相关产品推荐
相关产品推荐

