问题描述:
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.
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(len>mLen)
{
pMS=pStart;
mLen=len;
}
while(*pStart!=*p)
{
Table[*pStart]=0;
/* printf("%d\t",i);
printf("\n");*/
pStart++;
i++;
}
pStart++;
i++;
/*printf("%d\t",i);*/
}
else
{
Table[*p]=1;
len++;
}
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);
}