3. Longest Substring Without Repeating Characters

问题描述:

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be asubstring, "pwke" is a subsequence and not a substring.

解题思路:

从该题目中,可以看出,只需在一个字符串中找到最长的不同的子串。以abcbef这个串为例,用一个数据结构pos记录每个元素曾出现的下标,初始为-1,从s[0]开始,pos['a']==-1,说明a还未出现过,令pos['a']=0,视为将a“加入当前串”,同时长度++。同理令pos['b']=1,pos['c']=2,到s[3]时,pos['b']!=-1,说明'b'在前面已经出现过了,此时可得到一个不重复串“abc”,刷新当前的最大长度,然后做如下处理:pos[s[0~2]]=-1,即将“ab”“移除当前串”,同时当前长度减去3.

#include<stdio.h>
void GetMaxUnRepeatSubStr(char *str){
    int Table[256]={0};
    int i=0;
    char *pMS=str;
    int mLen=0;
    char *pStart=pMS;
    int len=mLen;
    char *p=pStart;
    while(*p!='\0')
    {
        if(Table[*p]==1)
        {
            if(len>mLen)
            {
                pMS=pStart;
                mLen=len;
            }
            while(*pStart!=*p)
            {
                Table[*pStart]=0;
              /*  printf("%d\t",i);
                printf("\n");*/
                pStart++;
                i++;
                len--;
            }
            pStart++;
            i++;
             /*printf("%d\t",i);*/
        }
        else
        {
            Table[*p]=1;
            len++;
        }
        p++;
    }
    if(len>mLen)
    {
        pMS=pStart;
        mLen=len;
    }
    while(mLen>0)
    {
       printf("%c",*pMS);
        mLen--;
        pMS++;
    }
    printf("\n");
}
int main()
{
    char *str1="bdabcdcf";
    GetMaxUnRepeatSubStr(str1);
    char *str2="abcdefb";
    GetMaxUnRepeatSubStr(str2);
    char *str3="abcbef";
    GetMaxUnRepeatSubStr(str3);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lee1xf520

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值