字符串面试题系列之二:连续最长数字串

前言

 这是字符串的第二个算法,比起第一个算法来说,稍微难一点。不过没关系。多练习练习多写一写多记忆一下也是好的。

正文

 今天的算法是 连续最长字符串。题目如下:

题目】在字符串中找出连续最长的数字串,并把这个串的长度返回,并把这个最长数字串付给其中一个函数参数outputstr所指内存。

【例子】“abcd12345ed125ss123456789”的首地址传给intputstr后,函数将返回9outputstr所指的值为123456789

 【分析】对于这一道题来讲,求最长连续数字串,我们应该如何来思考呢?看完这道题我想,我和我的小伙伴们的脑海里立马就有了计数器的概念,我们可以对字符串中的每个数字串计数嘛,然后比较得到最大的。这就是我们所要求的最大连续数字串。那我们还要做什么呢。当然记住这个最大串的开始位置,还有最大串的长度
基于上面的想法,我们就有了初步的算法思路了。接下来我就就一步一步来实现这个算法。
第一步:我们首先遍历这个字符串;
第二步:判断,如果遇到的字符属于0~9,则将计数器加加;否则,我们应该统计刚才的数字串的长度和最大长度比较,如果大于最大长度,则重新设置最大长度,并记住数字串开始位置。
第三步:返回我们所需要的最大长度和数字串了。
 
再在上面文字思路的基础上,我们写下如下的code:
#include <iostream>
#include <cstring>

void find_max_number(char string[],int length,int &count, char *result )
{
   /* max_length represents the max length of number string. */
   int max_length = 0;
   /* start means first character's position of number string */
   int start = 0;
   /* i represents iterator of string array */
   int i = 0;
   // here we scan the character array.
   for( ; i < length; i++ )
   {
      // if character belongs to 0~9 we add counter.
      // otherwise we set counter as 0.
      if( string[i] >= '0' && string[i] <= '9' )
      {
         count ++;
      }
      else
      {
         if( count > max_length )
         {
            max_length = count;
            start = i - count + 1;
         }
         count  = 0;
      }
   }
   // finally we should set max_length and the position again.
   if( count > max_length )
   {
      max_length = count;
      start = i - count;
   }
   // the last, we return counter and the string we need.
   count = max_length;
   memcpy( result, &string[start], count*sizeof(char) );
}

int main( int argc, char ** argv )
{
   char string[] = "iabcd12345ed125ss123456789";
   char result[20] = {0};
   int count = 0;
   find_max_number( string, strlen(string), count, result );
   std::cout << count << " " << result << std::endl;
   return 0;
}

总结

我们输入字符串
abcd12345ed125ss123456789,得到的结果如下:
《字符串面试题系列之二:连续最长数字串》



作者:Alex
出处:http://blog.csdn.net/hellotime
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

点赞