int lengthOfLongestSubstring(string s) {
int n = s.size();
if (n <= 1)
{
return n;
}
int i = 0;//start of the current checking string
int j = 1;//end of the current checking string
int len = 0;
int max_len = 0;
while (j < n){
for (int k = i; k < j; ++k){//k is current index between i and j
if (s[j] == s[k]){ //always comparing from i...k...j
max_len = max_len>len ? max_len : len;//if find a duplicated one check which is the larger one
len = 1; //start to re-calculate length
++i; //start next checking from j
//i = j won't work at cornercase:"abac"
j = i + 1; //j goto to next element
break;
}
else{
if (k == j -1){ //make sure it's the last char in this turn
len = j - i + 1;//calculate length only when compared the last char in this turn e.g. "abb"
++j;
break; // here needs a break. if not, j+1, for loop will continue, but actually we finished the check in this turn
}
}
}
}
//if program goes here, that means we checked the whole string(j is at the end of string s).
//maybe there are duplicated words, maybe not. So we need to check len and max_len
len = j - i; // here, len shouldn't be j - i + 1, because before while loop is over, j already +1
return max_len>len ? max_len : len;
}
只想到了这个方法,但因为大字符串,计算超时,没有通过leetcode。
3. Longest Substring Without Repeating Characters
最新推荐文章于 2021-12-03 15:58:56 发布