LeetCode-Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: 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,考慮左右指針如何向右移動

          2,注意邊界,何時退出

          3,如何判斷兩個指針之間字母無重複

代碼:

class Solution {public:    map<char,int> count;    int lengthOfLongestSubstring(string s) {        if(s.length()==0) return 0;        int left,right;        int ans = 1;               left=0;        right=0;        count[s[right]]+=1;        right++;        while(1)        {            if(right>=s.length()) break;                        count[s[right]]+=1;                        while(count[s[right]]>1)            {                count[s[left]]--;                left++;            }            ans = max(ans,right-left+1);                        right++;                   }        return ans;    }};
發佈了174 篇原創文章 · 獲贊 20 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章