本文共 3230 字,大约阅读时间需要 10 分钟。
题目
描述:
请一个在字符串中找出连续最长的数字串,并把这个串的长度返回;如果存在长度相同的连续数字串,返回最后一个连续数字串;注意:数字串只需要是数字组成的就可以,并不要求顺序,比如数字串“1234”的长度就小于数字串“1359055”,如果没有数字,则返回空字符串(“”)而不是NULL!
样例输入
abcd12345ed125ss123058789abcd12345ss54761
样例输出
输出123058789,函数返回值9输出54761,函数返回值5
函数原型:
unsignedint Continumax(char** pOutputstr, char* intputstr)
输入参数:
char* intputstr 输入字符串;
输出参数:
char** pOutputstr: 连续最长的数字串,如果连续最长的数字串的长度为0,应该返回空字符串;如果输入字符串是空,也应该返回空字符串;
返回值:
连续最长的数字串的长度
练习阶段:
初级
代码一
/*---------------------------------------* 日期:2015-07-03* 作者:SJF0115* 题目:在字符串中找出连续最长的数字串* 来源:华为机试练习题-----------------------------------------*/#include#include #include #include "oj.h"using namespace std;/* 功能:在字符串中找出连续最长的数字串,并把这个串的长度返回函数原型: unsigned int Continumax(char** pOutputstr, char* intputstr)输入参数: char* intputstr 输入字符串输出参数: char** pOutputstr: 连续最长的数字串,如果连续最长的数字串的长度为0,应该返回空字符串 pOutputstr 指向的内存应该在函数内用malloc函数申请,由调用处负责释放返回值: 连续最长的数字串的长度 */unsigned int Continumax(char** pOutputstr, char* intputstr){ if(intputstr == NULL){ return 0; }//if int size = strlen(intputstr); *pOutputstr = new char[size+1]; int start = 0,end = 0,maxStart = 0,maxEnd = 0; int max = 0; for(int i = 0;i < size;++i){ // 数字 int count = 0; start = i; // 统计连续数字 while(i < size && intputstr[i] >= '0' && intputstr[i] <= '9'){ ++i; ++count; }//if // 更新最大值 if(max <= count){ max = count; maxStart = start; maxEnd = i; }//if }//for //输出 int index = 0; for(int i = maxStart;i < maxEnd;++i){ (*pOutputstr)[index++] = intputstr[i]; }//for (*pOutputstr)[index] = '\0'; return maxEnd - maxStart;}
代码二
/*---------------------------------------* 日期:2015-07-03* 作者:SJF0115* 题目:在字符串中找出连续最长的数字串* 来源:华为机试练习题-----------------------------------------*/#include#include #include #include "oj.h"using namespace std;/* 功能:在字符串中找出连续最长的数字串,并把这个串的长度返回函数原型: unsigned int Continumax(char** pOutputstr, char* intputstr)输入参数: char* intputstr 输入字符串输出参数: char** pOutputstr: 连续最长的数字串,如果连续最长的数字串的长度为0,应该返回空字符串 pOutputstr 指向的内存应该在函数内用malloc函数申请,由调用处负责释放返回值: 连续最长的数字串的长度 */unsigned int Continumax(char** pOutputstr, char* intputstr){ if(intputstr == NULL){ return 0; }//if int size = strlen(intputstr); *pOutputstr = new char[size+1]; int start = 0,end = 0,maxStart = 0,maxEnd = 0; int max = 0; bool isNum = false; for(int i = 0;i <= size;++i){ // 数字 if(intputstr[i] >= '0' && intputstr[i] <= '9'){ ++end; isNum = true; }//if // 非数字 else{ if(isNum || i == size){ if(max <= (end - start)){ max = end - start; maxStart = start; maxEnd = end; }//if }//if start = i + 1; end = i + 1; isNum = false; }//else }//for //输出 int index = 0; for(int i = maxStart;i < maxEnd;++i){ (*pOutputstr)[index++] = intputstr[i]; }//for (*pOutputstr)[index] = '\0'; return maxEnd - maxStart;}
转载地址:http://zwfpl.baihongyu.com/