首页 > 代码库 > 【35】3. Longest Substring Without Repeating Characters

【35】3. Longest Substring Without Repeating Characters

3. Longest Substring Without Repeating Characters

  • Total Accepted: 244703
  • Total Submissions: 1029071
  • Difficulty: Medium
  • Contributors: Admin

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.

 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstring(string s) {
 4         int m[256] = {-1};
 5         int left = 0;
 6         //int right = 0;//不需要用到right,往右走的时候直接用i替代即可
 7         int res = 0;
 8         for(int i = 0; i < s.size(); i++){
 9             if(m[s[i]] == 0 || m[s[i]] < left){
10                 res = max(res, i - left + 1);
11             }else{
12                 left = m[s[i]];//更新左边界
13             }
14             m[s[i]] = i + 1;//这样赋值,记录的是下次的最左边界可以到哪里
15         }
16         return res;
17     }
18 };

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 
 

【35】3. Longest Substring Without Repeating Characters