题目
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.
思路
采用哈希的思想,建立数组,映射字符串,记录字符串每个字符出现的位置。
最长无重复子串肯定包含在两个重复字符之间,或者,没有重复时,从头到尾。
遇到重复字符(哈希数组中记录了一个位置),更新起始位置。
每前进一个位置,将最大值与当前位置与起始位置的差比较更新最大值。
代码
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; } };