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 asubsequence and not a substring.
int length = 0, len=0;
char *temp = (char*)malloc(sizeof(char));
bool flag = 0;
int Cnt = 0;
temp = s;
if(*s)
{
length++;
s++;
}
else
{
return length;
}
while(*s)
{
while(*temp||Cnt == length)
{
if(*s == *temp)
{
flag = 1;
break;
}
temp--;
Cnt++;
}
if(flag == 0)
{
temp=s;
length++;
}
else
{
if(len < length)
{
len = length;
}
temp = s;
length = 1;
}
s++;
}
if(len > length)
{
length = len;
}
return length;
}
上方案只通过了1/6的测试用例,原因:初始化的问题,需要细心考虑逻辑;
修改:
int lengthOfLongestSubstring(char* s) {
int length = 0, len=0;
char *temp = (char*)malloc(sizeof(char));
bool flag = 0;
int Cnt = 0;
temp = s;
if(*s)
{
length++;
s++;
}
else
{
return 0;
}
while(*s)
{
Cnt = 0;
flag = 0;
while(Cnt < length)
{
if(*s == *temp)
{
flag = 1;
break;
}
temp--;
Cnt++;
}
if(flag == 0)
{
temp=s;
length++;
}
else
{
if(len < length)
{
len = length;
}
temp = s;
length = 1;
}
s++;
}
if(len > length)
{
length = len;
}
return length;
}
改过之后:通过率为百分之五十,未通过用例为:"dvdf"
思考:考虑的情况不全面;
别人的优质解答:
int lengthOfLongestSubstring(char* s)
{
int len=0;
char *end=s,*temp;
char* addressTable[128]={NULL};
while(*end){
temp = addressTable[*end];
addressTable[*end]=end;
if(temp>=s){
len=end-s>len?end-s:len;
s = temp+1;
}end++;
}
len=end-s>len?end-s:len;
return len;
}
以上答案还未理解,未完待续……
对优质答案的理解:运用哈希表的思想,用字符作为索引,addressTable[128]数据表示索引的地址,128表示前128个ASCII字符,temp表示
addressTable
未更新前end指针所指向字符地址,addressTable[128]
存储不断更新的字符地址,一旦存在重复字符,s指针更新为temp+1(指被重复的字符存储地址加1),长度更新;循环体结束后,表示重复字符已经找完,再次更新长度(次算法简洁精妙,学习了~补hash表知识点,其将数组与指针运用得非常灵活!!!)
疑问:!另外,由于数组存储的是地址,因此它存储的是字符指针!!!(试过将char指针数组改为int型数组,也可得到同样结果,但是建议不要如此,因为不知道地址值得上下限,所以还是取字符指针数组)