题解 | #在字符串中找出连续最长的数字串#
在字符串中找出连续最长的数字串
http://www.nowcoder.com/practice/2c81f88ecd5a4cc395b5308a99afbbec
用一个ArrayList记录目前为止最长数字字符串的起点, 用一个int记录目前为止最长数字字符串长度, 就可以通过一次遍历来找出结果.
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
while(in.hasNextLine()){
String str = in.nextLine();
System.out.println( find_longest_numeric(str) );
}
}
public static String find_longest_numeric(String str){
str += ".";//给str加一个结尾符号
ArrayList<Integer> startIndex_list = new ArrayList<Integer>(); //最长的数字字符串的起点(>=1)
int max_len = 0;//最长的数字字符串的长度
int len = 0;//当前数字字符串的长度
int start_index = -1;//当前数字字符串的起点
for(int i=0;i<str.length();i++){
char cr = str.charAt(i);
if(Character.isDigit(cr)){// 这一位是数字
len++;
if(len==1){//如果这是数字字符串的第一位,更新 start_index 为 i
start_index = i;
}
}else{// 这一位不是数字
if(len > max_len){//如果这个数字字符串的长度比 max_len 记录要长
max_len = len;//更新 max_len
startIndex_list.clear();//删除 ArrayList 以前的所有记录
startIndex_list.add(start_index);//添加这一数字字符串的起点
}else if(len == max_len){//如果这个数字字符串的长度和 max_len 记录相同
startIndex_list.add(start_index);//添加这一数字字符串的起点
}
//重置 数字字符串长度变量len 和 数字字符串起点start_index
len = 0;
start_index = -1;
}
}
//整理并返回结果
String result = "";
for(int index : startIndex_list ){
result+=str.substring(index, index+max_len);
}
result = result + "," + max_len;
return result;
}
}
曼迪匹艾公司福利 148人发布
