题解 | 在字符串中找出连续最长的数字串
在字符串中找出连续最长的数字串
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();
}
}
一维动态规划