您的位置:首页 > 其它

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

2017-01-13 00:00 375 查看

题目描述

样例输出
输出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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐