题目要求:
读入一个字符串str,输出字符串str中的连续最长的数字串
输入描述:
个测试输入包含1个测试用例,一个字符串str,长度不超过255。
输出描述:
在一行内输出str中里连续最长的数字串。
示例:
输入:abcd12345ed125ss123456789
输出:123456789
思路:
用 end 记录最长字符串最后一位数字的下标,用 max 记录最长数字串的最大值,count 表示数字计数器,当遇到字母时重置为 0 。每次满足数字时对 max 进行判断,当 max 小于 count 时,更新 max 和 end ,最后根据下标用字符串的 substring 函数截取并返回结果。
具体实现代码如下:
import java.util.Scanner;
public class Test4_13_1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String str = sc.nextLine();
System.out.println(numberStr(str));
}
}
public static String numberStr(String str){
int max = 0,count = 0,end = 0;
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i) >= '0' && str.charAt(i) <= '9'){
count++;
if(max < count){
max = count;
end = i;
}
}else{
count = 0;
}
}
return str.substring(end - max + 1,end + 1);
}
}