题解 | #在字符串中找出连续最长的数字串#

在字符串中找出连续最长的数字串

http://www.nowcoder.com/practice/2c81f88ecd5a4cc395b5308a99afbbec

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String str = sc.nextLine();
            // 数字串长度 -> 等于此长度的数字串合并串
            Map<Integer, String> map = new HashMap<>();
            int len = 0;
            int i = 0, j = 0;
            // 双指针
            // j先走,碰到数字时,i = j, j继续走,知道遇到字母时且i处是数字,计算长度
            // 然后,i=j,
            while (j < str.length()) {
                if (str.charAt(j) <= '9') {// j遇到数字了
                    if (str.charAt(i) > '9') { //i处是字母
                        i = j;
                    }
                    j++; // 只有当j是字母时,调整i,j继续走
                } else {//j处是字母
                    if (str.charAt(i) <= '9' && j - i >= len) {//i处是数字,就可以计算了
                        len = j - i;
                        map.put(len, map.getOrDefault(len, "") + str.substring(i, j));
                    }
                    i = j;//j处是字母的话,无论如何,i都要走到j的位置,j继续走
                    j++;
                }
            }
            // 末尾可能为数字,只有j是字母时才触发
            if (str.charAt(j - 1) <= '9' && j - i >= len) {
                len = j - i;
                map.put(len, map.getOrDefault(len, "") + str.substring(i, j));
            }
            System.out.println(map.get(len) + "," + len);
        }                
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务