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

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

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String s = in.nextLine();
            int max = 0;
            int count = 0;
            StringBuilder temp =  new StringBuilder();
            StringBuilder res =  new StringBuilder();
            for (int i = 0; i < s.length(); i++) {
                if (Character.isDigit(s.charAt(i))) {
                    temp.append(s.charAt(i));
                    count++;
                } else {
                    if (count > max) {
                        max = count;
                        res = temp;
                    } else if (count == max) {
                        res.append(temp);
                    }
                    count = 0;
                    temp = new StringBuilder();
                }
            }
            if (count > max) {
                max = count;
                res = temp;
            } else if (count == max) {
                res.append(temp);
            }
            res.append(",").append(max);
            System.out.println(res);
        }

    }
}

全部评论

相关推荐

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