Leetcodes Solution 3 Longest Substring Without Repeating Characters
匯總
雪之下雪乃:leetcode解題總匯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
用dict來存儲字元和它出現的索引。start表示目前不相同的子字元串的開頭索引。
用i-start得到所有不相同的子字元串的長度,在比較求出最大的
class Solution{public: int lengthOfLongestSubstring(string s){ vector<int> dict(256, -1); int maxLen = 0, start = -1; for(int i = 0; i != s.length(); i++){ if(dict[s[i]] > start) start = dict[s[i]]; dict[s[i]] = i; maxLen = max(maxLen, i - start); } return maxLen; }};
推薦閱讀:
※自動駕駛還在盯著「演算法」和「感測器」么?風河打算為其開發通用底層操作系統了
※矩陣中的路徑
※Search in Rotated Sorted Array的升級
※027 Remove Element[E]