美團筆試題(在字符串中找出連續最長的數字串)

package com.suanfa.meituan;

import java.util.Scanner;

public class Test2 {


/**
* 描述:在字符串中找出連續最長的數字串
* 例如
* 輸入:abc123defg45678hijk1901m
* 輸出:45678
* 輸入:abcd12345ed125ss123058789
* 輸出:123058789
*/

public static int getResult(String instr,String  outstr) {
int maxlength=0;
StringBuffer maxNumberStr=null;

int nowlength=0;
StringBuffer nowNumberStr=null;

for(int i=0;i<instr.length();i++){
if((instr.charAt(i)>=48)&&(instr.charAt(i)<=57)){
if(nowlength==0){
nowNumberStr=new StringBuffer(String.valueOf(instr.charAt(i)));
nowlength++;
}else{
nowNumberStr.append(instr.charAt(i));
nowlength++;
}
if(nowlength>=maxlength){
maxlength=nowlength;
maxNumberStr=nowNumberStr;
}
}else{
nowlength=0;
nowNumberStr=null;
}
}
System.out.println(maxNumberStr);
return maxlength;
}

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
String str=sc.nextLine();
System.out.println(getResult(str,null));
}
}
}
發佈了34 篇原創文章 · 獲贊 12 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章