在字符串中找出連續最長的數字串

題目描述

樣例輸出
    輸出123058789,函數返回值9
    輸出54761,函數返回值5

輸入描述

輸入一個字符串。

輸出描述

輸出字符串中最長的數字字符串和它的長度。

輸入例子

abcd12345ed125ss123058789

輸出例子

123058789,9

算法實現

import java.util.Scanner;

/**
 * Declaration: All Rights Reserved !!!
 */
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
//        Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
        while (scanner.hasNext()) {
            String input = scanner.nextLine();
            System.out.println(maxNum(input));
        }

        scanner.close();
    }

    private static String maxNum(String s) {

        int max = 0;
//        int idx = 0;
        int cur = 0;
        String result = "";

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= '0' && c <= '9') {
                cur++;
                if (max < cur) {
                    max = cur;
//                    idx = i;
                    result = s.substring(i - max + 1, i + 1);
                } else if (max == cur) {
                    result += s.substring(i - max + 1, i + 1);
                }
            } else {
                cur = 0;
            }
        }

        return result + "," + max;
    }
}
相關文章
相關標籤/搜索