您的位置:首页 > 其它

微软算法100题25 查找连续最长的数字串

2015-10-26 11:21 288 查看
第25 题:
写一个函数,它的原形是int continumax(char *outputstr,char *intputstr)
功能:
在字符串中找出连续最长的数字串,并把这个串的长度返回,
并把这个最长数字串付给其中一个函数参数outputstr 所指内存。
例如:"abcd12345ed125ss123456789"的首地址传给intputstr 后,函数将返回9,
outputstr 所指的值为123456789

思路:两个指针,一个保存当前最长长度的变量max,然后移动指针,直到到字符串尾即可

package com.rui.microsoft;

public class Test25_FindLongestDigitString {

public static void main(String[] args) {
String s = "abcd12345ed125ss12345678900adb11";
int max = find(s);
System.out.println(max);
}

public static int find(String s){
if(null == s || s.isEmpty()) return 0;
char[] chars = s.toCharArray();
int max = 0;
int start = 0, cur = 0;
int len = chars.length;
while(cur < len){
while(cur < len && !isDigit(chars[cur])){
cur++;
}
start = cur;
while(cur < len && isDigit(chars[cur])){
cur++;
}
max = max > (cur - start) ? max : (cur-start);
}

return max;
}

private static boolean isDigit(char c){
return c >= '0' && c <= '9';
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: