美团笔试题(在字符串中找出连续最长的数字串)

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 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));
}
}
}

你可能感兴趣的:(算法与数据结构)