[LeetCode] Longest Substring Without Repeating Characters


Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

用兩個指針,一個指向當前子串的頭,一個指向尾,尾指針不斷往后掃描,當有字符前面出現過了,記錄當前子串長度和最優解的比較結果。然后頭指針不斷往后掃描,直到掃描到一個字符和尾指針相同,則尾指針繼續掃描,當尾指針到達字符串結尾,算法結束。復雜度O(n) + O(n) = O(n)

 1 class Solution {
 2 private:
 3     bool canUse[256];
 4 public:
 5     int lengthOfLongestSubstring(string s) {
 6         // Start typing your C/C++ solution below
 7         // DO NOT write int main() function
 8         memset(canUse, true, sizeof(canUse));
 9         
10         int count = 0;
11         int start = 0;
12         int ret = 0;
13         for(int i = 0; i < s.size(); i++)
14         {
15             if (canUse[s[i]])
16             {
17                 canUse[s[i]] = false;
18                 count++;
19             }
20             else
21             {
22                 ret = max(ret, count);
23                 while(true)
24                 {
25                     canUse[s[start]] = true;
26                     count--;
27                     if (s[start] == s[i])
28                         break;
29                     start++;
30                 }
31                 start++;
32                 canUse[s[i]] = false;
33                 count++;
34             }
35         }
36         
37         ret = max(ret, count);
38         
39         return ret;
40     }
41 };

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM