3. Longest Substring Without Repeating Characters

≡放荡痞女 提交于 2020-02-12 00:26:27

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 };

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!