From 168d7ca6d11d99be2b38bdb75062c676e3138d83 Mon Sep 17 00:00:00 2001 From: nonstriater <410495266@qq.com> Date: Wed, 2 Dec 2015 16:46:09 +0800 Subject: [PATCH] add longest_continuious_number --- 算法问题选编/字符串.md | 110 +++++++++++++++--- .../测试代码/longest_continuious_number.c | 56 +++++++++ 2 files changed, 148 insertions(+), 18 deletions(-) create mode 100644 算法问题选编/测试代码/longest_continuious_number.c diff --git a/算法问题选编/字符串.md b/算法问题选编/字符串.md index abc5f1b..04f3404 100644 --- a/算法问题选编/字符串.md +++ b/算法问题选编/字符串.md @@ -333,6 +333,33 @@ char *delete_occurence_characterset(char *source,const char *del); +#### 删除字符串中的数字并压缩字符串 + +如字符串”abc123de4fg56”处理后变为”abcdefg”。注意空间和效率。(下面的算法只需要一次遍历,不需要开辟新空间,时间复杂度为O(N)) +这道题跟上一道题也是一个意思。 + + +示例代码: + +``` +char *trim_number(char *source){ + char *start = source; + char *end = source; + if (source == NULL) return NULL; + while(*end != '\0'){ + if (*end < '0' || *end > '9' ){ + *start = *end; + start++; + } + end++; + } + *start = '\0'; + return source; +} +``` + + + #### 字符串原地压缩 题目描述:“abeeeeegaaaffa" 压缩为 "abe5ag3f2a",请编程实现。 @@ -356,13 +383,69 @@ char *compress(const char *src,char *dest){ -#### 删除字符串中的数字并压缩字符串 -如字符串”abc123de4fg56”处理后变为”abcdefg”。注意空间和效率。 -(下面的算法只需要一次遍历,不需要开辟新空间,时间复杂度为O(N)) +#### 字符串中找出连续最长的数字串 + +写一个函数,功能: + +在字符串中找出连续最长的数字串,并把这个串的长度返回,并把这个最长数字串赋值给其中一个函数参数outputstr所指内存。 + +例如:"abcd12345ed125ss123456789"的首地址传给intputstr后,函数将返回9,outputstr所指的值为123456789 + +它的原形是: ``` -void trim_number(char *source); +int longest_continuious_number(const char *input,char *output) +``` + +应该有3个指针,第一个指针指向一个当前最长数字串的第一个数字,第二个指针指向第二个数字串的第一个数字,第三个指针是遍历指针,且统计第二个数字串的长度;当统计出来的长度大于第一个数字串的长度,第一个指针指向第二个指针指向的数字,相反,第二个指针和第三个指针继续向后查找。 + +当end首次碰到数字时,且max=0,说明是首次出现数字,第一个/二个指针移到该数字,继续遍历 +end首次碰到数字,且max!=0,说明出现第二个数字串,tmp=1 +如果数字后面还是数字,tmp!=0 就是第二个数字串,因此 tmp += 1; 否则还是max += 1; +当end从数字到普通字符时,如果tmp!=0,就要比较 tmp 和 max + +``` +int longest_continuious_number(const char *input,char *output){ + int max = 0; + char *start= input; + char *mid = input; + char *end = input; + int tmp = 0; + if (input == NULL || output == NULL) return 0; + + while (*end != '\0'){ + if (*end < '0' || *end < '9'){//字母 + if(tmp > max){ + max = tmp; + start = mid; + } + tmp = 0; + }else{//数字 + if (tmp == 0){//发现数字 + mid = end; + } + tmp++; + } + end++; + } + + //修改已数字结尾的bug + if(tmp > max){ + max = tmp; + start = mid; + } + + //copy + int i=0; + while(i '9'){//字母 + if(tmp > max){ + max = tmp; + start = mid; + } + tmp = 0; + }else{//数字 + if (tmp == 0){//发现数字 + mid = end; + } + tmp++; + } + end++; + } + + //修改已数字结尾的bug + if(tmp > max){ + max = tmp; + start = mid; + } + + //copy + int i=0; + while(i