字符串中找出连续最长的数字串
题目:牛客网
解题思路:
遍历字符串,对每一个字符判断是否为数字
如果是数字则更新记录长度加一,记录其位置,与最大长度作比较取大的长度
如果不是数字则记录长度更新为0
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
while(in.hasNext()){
String str = in.nextLine();
int end_pos = 0;
int max_len = 0;
int temp_max = 0;
for(int i =0 ; i < str.length(); i++){
if((str.charAt(i) >= '0') && (str.charAt(i) <= '9') ){
temp_max++;
if(temp_max > max_len){
max_len = temp_max;
end_pos = i;
}
}
else{
temp_max = 0;
}
}
System.out.println(str.substring(end_pos+1-max_len, end_pos +1 ));
}
}
}