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

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

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);
        // 注意 hasNext 和 hasNextLine 的区别
        String str;
        boolean flag = true;//是第一个数字
        StringBuilder sb = new StringBuilder();

        while (in.hasNextLine()) { // 注意 while 处理多个 case
            str = in.nextLine();
            int count = 0;
            int temp = 0;
            //2kn1dt0366
            for (int i = 0; i < str.length(); i++) {
                if ( str.charAt(i) >= '0' && str.charAt(i) <= '9' && flag == true) {
                    count++;
                    flag = false;
                } else if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
                    count++;
                } else{
                    flag = true;
                    if(temp < count)
                    temp = count;
                    count = 0;
                    
                }
            }
            if(temp < count){
                temp = count;
            }
            flag = true;
            count = 0;
            for (int i = 0; i < str.length(); i++) {
                if ( str.charAt(i) >= '0' && str.charAt(i) <= '9' && flag == true) {
                    count++;
                    sb.append(str.charAt(i));
                    flag = false;
                } else if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
                    count++;
                    sb.append(str.charAt(i));
                    if (temp == count) {
                        System.out.print(sb.toString());
                    }
                    flag =false;
                }else{
                    count = 0;
                    flag = true;
                    sb.setLength(0);
                }
            }
            System.out.println("," + temp);
        }
    }
}

全部评论

相关推荐

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