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 a substring, "pwke"
is a subsequence and not a substring.
分析:
我的想法是使用三个值front、back和mid分别指向子串的头尾和中间进行遍历,如下为遍历过程:
- back每次加一
- back加一后,mid对从front开始到back之前的元素进行遍历,并判断mid和back所在位置的元素值是否相同
- 如果相同,front指向mid+1位置元素,然后break跳出mid的遍历
- 如果不相同则mid++继续遍历直到相同或mid==back-1
- 如果front到back之前的元素均与back不相同,则将back-front+1和现存最大的字串长度相比较,取大的赋给max。
代码:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int max = 0;
int len = s.size();
if(len>0) max = 1;
int front = 0;
int back = front + 1;
int mid = front;
while(back<len){
mid = front;
bool flag = false;
do{//用mid对从front到back之前的值进行遍历
if(s[mid]==s[back]){//如果相同,字串头指向mid后一位
front = mid+1;
flag = true;
break;
}else{//不相同继续遍历
mid++;
}
}while(mid<back);
//如果front到back无重复元素,则将该子串长度与max比较,将最大的赋给max
if(!flag) max = max<back-front+1?back-front+1:max;
back++;
}
return max;
}
};