题解 | #在字符串中找出连续最长的数字串#

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

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;

    }

}
全部评论

相关推荐

开发转测第二人:没实习的话,两个项目吧,八股也要准备一下,这个时间点有点小晚了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务