Day27: [LeetCode中等] 3. 無重複字符的最長子串

Day27: [LeetCode中等] 3. 無重複字符的最長子串

題源:

來自leetcode題庫:

https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
### 思路:
這題我用的方法有點小笨,首先設置左右下標,分別指向最長無重複字串的兩端,遍歷字符串,依次放進set裏,然後遇到相同的就回溯,回溯到相同的字符那裏,更改左右下標,同時更新長度最大值。
### 代碼:
dirty code湊合看吧

class Solution {
public:
int lengthOfLongestSubstring(string s) {
int L=s.size();
if(L0) return 0;
if(L
1) return 1;
int l=0,r=0;
unordered_set se;
int max=0;
for(int i=1;i<L;i++){
int j;
for(j=r;j>=l;j–){
if(s[j]==s[i]){
l=j+1;
r=i;
break;
}
}
if(j<l){
r=i;
}
max=max>r-l?max:r-l;
}
return max+1;
}
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章