Given a string, find the length of the longest substring without repeating characters.spa
Example 1:code
Input: "abcabcbb" Output: 3 Explanation: The answer is , with the length of 3. "abc"
Example 2:blog
Input: "bbbbb" Output: 1 Explanation: The answer is , with the length of 1. "b"
Example 3:字符串
Input: "pwwkew" Output: 3 Explanation: The answer is , with the length of 3. Note that the answer must be a substring, is a subsequence and not a substring.
最長不含重複字符的子字符串
C++:"wke""pwke"
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 };