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.
分析:题意为给一个字符串,找出最长的没有重复字符的子串。
思路:用一个数组来记录目前字符串中出现过的字符(出现过记为1,未出现记为0),start表示满足条件的字符串的起始位置,i每次往前移动一次,遇到一个新的字符元素,判断当前的数组中是否已经存在这个字母,如果存在,移动i指针,直到排除之前出现过的这个元素。
代码:
class Solution { public: int lengthOfLongestSubstring(string s) { vector<int> sign(256, 0); int maxstr=0, start=0; for(int i=0;i<s.length();i++) { while(sign[s[i]]) sign[s[start++]]=0; sign[s[i]]=1; maxstr=max(maxstr, i-start+1); } return maxstr; } };
其它解法:
Solution 1(Original): using a set to maintain a window (bounded by l and r) only contains distinct chars. When there is a new character, adds to set, and move r forward; when it's a character that already exists, move l forward right next to the previous inserted character as s[r]. This is my original solution, but may have some overheads when erasing elements from set. Just a different perspective.
class Solution { public: int lengthOfLongestSubstring(string s) { if(s.size()<1) return s.size(); int l=0, r=0, len=1; unordered_set<char> window; while(r<s.size()){ if(window.find(s[r])==window.end()){ window.insert(s[r++]); len=max(len, r-l); }else{ while(s[l]!=s[r]) window.erase(s[l++]); l++; r++; } } return len; } };
Solution 2: The basic idea is, keep a hashmap which stores the characters in string as keys and their positions as values, and keep two pointers which define the potential max substring(window using my word). move the right pointer to scan through the string , and meanwhile update the hashmap. If the character is already in the hashmap, then move the left pointer to the right of the same character last found. Note that the two pointers can only move forward.
To understand l=max(l,window[s[r]]+1) is the key here:
If position of last found char same as s[r] is beyond l, which means the window will have two same chars s[r] now, so we need to move forward l to shrink the window. Otherwise, l stays the same. That's all what says. Your feedback or any thought is welcome. I really learnt a lot from all you genius.
Example 1 "tmmzuxt"
s[l] is the 2nd "m", s[r] is the last "t", and the last found t is not in the current window, no need to update l.
Example 2 "mmzuxtabt"
s[l] is the 2nd m, s[r] is the last "t", and the last found "t" is in the current window, so move lforward to "a".
class Solution { public: int lengthOfLongestSubstring(string s) { int l=0, r=0, len=0; unordered_map<char, int> window; while(r<s.size()){ if(window.find(s[r])!=window.end()) l=max(l,window[s[r]]+1); //see explain window[s[r]]=r; len=max(len,r-l+1); r++; } return len; } };