字符串中找出连续最长的数字串_牛客网

题目:字符串中找出连续最长的数字串
读入一个字符串 str,输出字符串str中连续最长的数字串。
输入描述:一个测试输入包含一个测试用例,一个字符串str,长度不超过255。
输出描述:在一行内输出str中连续最长的数字串。
示例1
输入:
abcd12345ed125ss123456789
输出:
123456789
思路:用两层循环判断,第一层用于记录是否为数字开始,第二层记录有多少个数字。
最后将最长的数字串从原字符串中截取出来。

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        String result = "";
        char[] array = str.toCharArray();
        int count = 0;
        for (int i = 0; i < array.length; i++) {
            if (array[i] >= '0' && array[i] <= '9') {
                count=1;
                int index = i;
                for (int j = i + 1; j < array.length; j++) {
                    if (array[j] >= '0' && array[j] <= '9') {
                        count++;
                        index = j;
                    } else {
                        break;
                    }
                }
                if (count > result.length()) {
                    result = str.substring(i, index + 1);//截取最长数字串
                }
            }else {
                continue;
            }
        }
        System.out.println(result);
    }
}
发布了71 篇原创文章 · 获赞 2 · 访问量 7480

猜你喜欢

转载自blog.csdn.net/weixin_42512675/article/details/103001023