具体算法为:从头到尾遍历字符串,每当遇到数字连续数字子串时,记录其长度。并与全局记录的最长长度相比较。如果更长的话,就记录当前长度和开始index。
public class LongestNumberSubstring {
public static int[] findLongestNumSubstring(String input) {
// If the string is empty, return [0, 0] directly.
if (input == null || input.length() == 0) {
return new int[]{0, 0};
}
int index = 0;
int[] ret = new int[]{0, 0}; //[start_index, length]
int currLen = 0;
while (index < input.length()) {
currLen = 0;
while (index < input.length() && Character.isDigit(input.charAt(index))) {
currLen++;
index++;
}
// If current substring is longer than or equal to the previously found substring
// Put it in return values.
if (currLen != 0 && ret[1] <= currLen