力扣 题目3- 无重复字符的最长子串

题目

题解

双重循环+左右边界

第一层循环遍历全部 作为右边界 第二层循环从left 左边界开始向右边界遍历

当 第一层循环与第二层循环字符串相等时 更新左边界为第二层循环+1 即可摆脱重复字符

每次循环完第二层 判断结果

代码

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 
 5 class Solution {
 6 public:
 7     int lengthOfLongestSubstring(string s) {
 8         int result= 0;
 9         int left = 0;
10         if (s.size()==0) {
11             return 0;
12         }
13         for (int i = 0; i < s.size(); i++) {
14             for (int j = left; j < i; j++) {
15                 if (s[i] == s[j]) {
16                     left = j+1;
17                 }
18             }
19             if (result < i - left + 1) {
20                 result = i - left + 1;
21             }
22         }
23         return result;
24     }
25 };
26 
27 int main() {
28     Solution sol;
29     string s = "abcabcbb";
30     int result=sol.lengthOfLongestSubstring(s);
31     cout << result << endl;
32 }
View Code

 

posted @ 2022-08-03 17:39  无聊的阿库娅  阅读(14)  评论(0编辑  收藏  举报