题解 | #在字符串中找出连续最长的数字串#java很简单的模拟,直接遍历就行

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

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

import java.io.*;
import java.util.*;

public class Main{
    public static void main(String[] args) throws Exception {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String str;
        while ((str = bf.readLine()) != null) {
            List<String> res = getLongSubString(str);
            for (String re : res) {
                System.out.print(re);
            }
            System.out.println("," + res.get(0).length());
        }
    }

    private static List<String> getLongSubString(String word) {
        int max = 0;
        int l = -1;
        List<String> res = new ArrayList<>();
        char[] ch = word.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            if (ch[i] <= '9' && ch[i] >= '0') {
                int len = i - l + 1;
                if (len > max) {
                    res.clear();
                    max = Math.max(max, len);
                    res.add(word.substring(l + 1, l + max));
                }else if (len == max) {
                    res.add(word.substring(l + 1, l + max));
                }
            } else {
                l = i;
            }
        }
        return res;
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务