问题描述
在字符串中找出连续最长的数字串,并将该串返回。(略有修改)
解决思路
双指针法。一前一后,注意保存最长连续数字串的开始或者结束位置和最长串的长度,最后返回该子串即可。
程序
public class LongestContinuousDigits {
public String getLCD(String s) {
if (s == null || s.length() == 0) {
return null;
}
int i = 0, j = 0;
int maxLen = 0, len = 0, idx = 0;
while (j < s.length()) {
if (!(s.charAt(j) >= '0' && s.charAt(j) <= '9')) {
i = j;
len = 0;
}
else if (!(s.charAt(i) >= '0' && s.charAt(i) <= '9')) {
// find the first character
i = j;
len = 1;
}
else {
if (s.charAt(j) == s.charAt(i) + 1) {
// continuous digits string
++i;
++len;
} else {
len = 0;
i = j;
}
}
if (len > maxLen) {
maxLen = len;
idx = j;
}
++j;
}
return s.substring(idx - maxLen + 1, idx + 1);
}
}