Description:
iven a string, find the length of the longest substring without repeating characters.
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 a substring, "pwke"
is a subsequence and not a substring.
Solution:
int lengthOfLongestSubstring(char* s) {
if(s[0]=='\0'){return 0;
}
int array=0; // 有多少字符
while(s[array]!='\0'){
array++;
}
int a[array]; //保存最长子串长度
int i=0;
while(i<array){
int sum=1; //统计s[i]开头的最长子串长度
int j;
j=i+1; //定位i后一位字符
while(j<array){ //看以s[i]为头的子串最长是多少
int k;
int flag=0; //是否有重复元素
for(k=i;k<j;k++){
if(s[k]==s[j]){ //s[j]前面有重复字符s[k],则s[i]的最大长度子串找到,将sum添加到链表
flag=1; //有重复元素
break;
}
}
if(flag==1){
a[i]=sum;
i++;
break;
}
else{
sum++;
j++;
if(j==array){
a[i]=sum;
i++;
}
continue;
}
}
if(i==array-1){
a[i]=1;
i++;
continue;
}
}
int max=a[0];
int p;
for(p=1;p<array;p++){
if(a[p]>max){
max=a[p];
}
}
return max;
}
Idea:1.判断字符串是否为空;2.遍历字符数组求其字符个数;3.由于子串是由连续字符组成,因此可以先计算字符串中每个字符形成的最大子串长度并保存在数组中;4.数组中的最大值即为所求
Summary:主要检查是否存在重复元素,以及边界处理即最后一个字符的最大子串长度为1,s[j]如果为最后一个字符则sum的值即为此时s[i]字符的最大子串长度。