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

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

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

 

 1 package com.rui.microsoft;
 2 
 3 public class Test25_FindLongestDigitString {
 4 
 5     public static void main(String[] args) {
 6         String s = "abcd12345ed125ss12345678900adb11";
 7         int max = find(s);
 8         System.out.println(max);
 9     }
10     
11     public static int find(String s){
12         if(null == s || s.isEmpty()) return 0;
13         char[] chars = s.toCharArray();
14         int max = 0;
15         int start = 0, cur = 0;
16         int len = chars.length;
17         while(cur < len){
18             while(cur < len && !isDigit(chars[cur])){
19                 cur++;
20             }
21             start = cur;
22             while(cur < len && isDigit(chars[cur])){
23                 cur++;
24             }
25             max = max > (cur - start) ? max : (cur-start);
26         }
27         
28         return max;
29     }
30     
31     private static boolean isDigit(char c){
32         return c >= '0' && c <= '9';
33     }
34 }

 

posted @ 2015-10-26 11:21  蟹粉小笼包  阅读(204)  评论(0编辑  收藏  举报