Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc"
, with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b"
, with the length of 1.
Example 3:
Input: "pwwkew" Output: 3 Explanation: 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.
最长不含重复字符的子字符串
C++:
1 class Solution { 2 public: 3 int lengthOfLongestSubstring(string s) { 4 int curLen = 0 ; 5 int maxLen = 0 ; 6 vector<int> preIndex(256 , -1) ; 7 for(int i = 0 ; i < s.length() ; i++){ 8 int pre = preIndex[s[i]] ; 9 if (pre == -1 || i - pre > curLen){ 10 curLen++ ; 11 }else{ 12 curLen = i - pre ; 13 } 14 preIndex[s[i]] = i ; 15 if (curLen > maxLen){ 16 maxLen = curLen ; 17 } 18 } 19 20 return maxLen ; 21 } 22 };