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

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

https://www.nowcoder.com/practice/2c81f88ecd5a4cc395b5308a99afbbec

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String str=in.nextLine();
            System.out.println(slove(str));
        }
    }

    static String slove(String str){
        int res=0;
        int len=str.length();
	  //dp[i]表示在以str第i个字符结尾的子串中,数字的最大长度
        int[] dp=new int[len+1];
        Queue<Integer> queue=new LinkedList<Integer>();
        for(int i=1;i<=len;i++){
            if(str.charAt(i-1)>='0'&&str.charAt(i-1)<='9'){
                dp[i]=dp[i-1]+1;
            }else{
                dp[i]=0;
            }
        }
        for(int j=1;j<=len;j++){
            if(dp[j]>res){
                res=dp[j];
                queue.clear();
                queue.offer(j);
            }else if(dp[j]==res){
                queue.offer(j);
            }
        }
        StringBuilder sb=new StringBuilder();
        if(res==0){
            return ","+res;
        }

        while(!queue.isEmpty()){
            int index=queue.poll();
            sb.append(str.substring(index-res,index));
        }
        sb.append(",");sb.append(res);

        return sb.toString();
    }
}

一维动态规划

全部评论

相关推荐

2025-12-15 12:50
河北工程大学
sta666:我也是这个国际商业化的,三天,一天一面,就通过了,不过我是后端实习生,好好面感觉能过。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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