1. 程式人生 > >【LeetCode & 劍指offer刷題】字串題15:48 最長不含重複字元的子字串(3. Longest Substring Without Repeating Characters)

【LeetCode & 劍指offer刷題】字串題15:48 最長不含重複字元的子字串(3. Longest Substring Without Repeating Characters)

【LeetCode & 劍指offer 刷題筆記】目錄(持續更新中...)

3. Longest Substrleftng Without Repeating Characters

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.     //找字串中的最長無重複字元的子串
/* 方法:Sliding Window 本質是列舉法 O(n) */ #include <unordered_set> #include <algorithm> class Solution { public :     int lengthOfLongestSubstring ( string s )     {               unordered_set <char> set//用hash表存滑動窗中的數,方便查詢是否有重複的數(用vector應該也可以,只不過hash表如果查詢得到元素時效率高一點)         int left  = 0 , right = 0 ; //雙指標,指向子串區間的左右兩端點         int max_length = 0 ;                 while ( right < s . size ())         {             if ( set . find ( s [ right ]) == set . end ()) //如果不是重複字元,插入字元,更新最大長度             {                 set . insert ( s [ right ++]);  //插入右邊元素,右指標加一                 max_length = max ( max_length , int ( set . size ())); //由於max函式只能對同類型的進行比較,這裡強制轉換             }             else //如果為重複字元,則移除區間首字元,直到set中不再含此字元為止(會多次判斷,多次執行移除操作)              {                 set . erase ( s [ left ++]); //移除左邊元素,左指標加一             }         }         return max_length ;     } };