`
kmplayer
  • 浏览: 512663 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

返回一个字符串无重复字符的最长子序列.

 
阅读更多
1,给出一个实例代码:
#include <iostream>
#include <cassert>
using namespace std;

//返回无重复字符的长度,head保存起点
int getNoCharLong(const char* str,int& head)
{
    bool isExist[26];
    memset(isExist,0,sizeof(isExist));

    const char* tmpS=str;
    int tmpHead=0,tmpTail=0;
    int maxLong=0,tmpLong=0;
    while (*tmpS != '\0')
    {
        assert((*tmpS >= 'a' ) && (*tmpS <= 'z'));
        if( !isExist[*tmpS-'a'] )
        {
            isExist[*tmpS-'a']=true;
            tmpLong++;
        }
        else
        {
            if(tmpLong>maxLong)
            {
                head=tmpHead;
                maxLong=tmpLong;
            }
            tmpHead=tmpTail;
            tmpLong=1;
            memset(isExist,0,sizeof(isExist));
            isExist[*tmpS-'a']=true;
        }
        tmpTail++;
        tmpS++;
    }
    if(tmpLong>maxLong)
    {
        head=tmpHead;
        maxLong=tmpLong;
    }

    return maxLong;
}

int main()
{
    char * str = "gkolmn";

    int maxLong,head=0;
    maxLong=getNoCharLong(str,head);
    cout<<maxLong<<endl;

    char* result=(char*)malloc(strlen(str)+1);
    strncpy(result,str+head,maxLong);
    *(result+maxLong)='\0';
    cout<<result<<endl;

    free(result);
    return 0;
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics