面经--连续最长数字串

如何连续最长数字串呢?本篇介绍一种C语言实现:

在字符串中找出连续最长的数字串,返回最长长度,并把这个最长数字串赋值给其中一个函数参数outputStr所指内存

“abcd12345ed125ss123456789”的首地址传给intputStr后,函数将返回9,outputStr所指的值为123456789

我们可以对字符串中的每个数字串计数,然后比较得到最大的。这就是我们所要求的最大连续数字串。需要记住这个最大串的开始位置,还有最大串的长度。
  1. 遍历字符串
  2. 如果遇到数字,则将计数器+1;否则,我们应该统计刚才的数字串的长度和最大长度比较,如果大于最大长度,则重新设置最大长度,并记住数字串开始位置
  3. 返回我们所需要的最大长度和数字串

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#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;
}

Powered by KyleCe

Copyright © 2015 - 2019 KyleCe All Rights Reserved.

访客数 : | 访问量 :