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.
首先建立一个256位大小的整型数组来表示哈希表,定义两个变量res和left,res记录最长无重复子串的长度,left记录最长无重复子串的起始位置。
然后遍历该字符串,对于每一个遍历到的字符,如果哈希表中该字符对应的值为-1, 则说明没有遇到过该字符,此时将该字符加入到最长无重复子串中,长度为i - left + 1, i为遍历到字符的位置。
还有一种情况也需要记录,当哈希表中的值小于left,这是由于此时出现过重复字符,但是left的位置更新了。
c++代码
1 class Solution { 2 public: 3 int lengthOfLongestSubstring(string s) { 4 vector<int> hash(256, -1); 5 int left = 0; 6 int res = 0; 7 for(int i = 0; i < s.size(); ++ i) 8 { 9 if(hash[s[i]] == -1 || left > hash[s[i]]) 10 res = max(res, i - left + 1); 11 else 12 left = hash[s[i]] + 1; 13 hash[s[i]] = i; 14 } 15 return res; 16 } 17 };