首页 > 其他 > 详细

ZT 查找字符串中连续最长的数字串

时间:2014-02-15 16:40:15      阅读:590      评论:0      收藏:0      [点我收藏+]

查找字符串中连续最长的数字串

题目:写一个函数,它的原型是如下,在字符串中找出连续最长的数字串,并把这个串的长度返回,并把这个最长数字串付给其中一个函数参数outputstr所指的内存。

int continuemax(char *outputstr, char *inputstr)

举例:intputstr被赋予"abcd12345ed125ss123456789",函数将返回9,outputstr所指的值为"123456789"。

答:

bubuko.com,布布扣
bubuko.com,布布扣
#include "stdafx.h"
#include <iostream>

using namespace std;

//查找字符串中连续最长的数字串
int continuemax(char *outputstr, char *inputstr)
{
    int maxLen = 0;
    char *pStart;
    char *maxStr;
    bool begin = true;
    int count = 0;
    while (*inputstr != \0)
    {
        if (begin && isdigit(*inputstr))
        {
            pStart = inputstr;
            count++;
            begin = false;
        }
        else if (isdigit(*inputstr))
        {
            count++;
        }
        else
        {
            if (count > maxLen)
            {
                maxStr = pStart;
                maxLen = count;
            }
            count = 0;
            begin = true;
        }
        inputstr++;
        if (*inputstr == \0 && count > maxLen)
        {
            maxStr = pStart;
            maxLen = count;
        }
    }
    *(maxStr + maxLen) = \0;
    while(*maxStr != \0)
    {
        *outputstr++ = *maxStr++;
    }
    *outputstr = \0;
    return maxLen;
}


int _tmain(int argc, _TCHAR* argv[])
{
    char inputstr[] = "abcd12345ed125ss123456789";
    char *outputstr = new char[strlen(inputstr) + 1];
    memset(outputstr, 0, strlen(inputstr) + 1);
    cout<<continuemax(outputstr, inputstr)<<"  "<<outputstr<<endl;
    delete [] outputstr;
    return 0;
}
bubuko.com,布布扣
bubuko.com,布布扣

运行界面如下:

bubuko.com,布布扣

分类: 算法面试

ZT 查找字符串中连续最长的数字串

原文:http://www.cnblogs.com/jeanschen/p/3550570.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!