【leetcode】3. Longest Substring Without Repeating Characters

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.


使用一个变量记录子字符串的左端点,注意当字符重复时长度的变化。
 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstring(string s) {
 4         int left = 0,res = 0,curRes = 0;
 5         vector<int> pos(256,-1);
 6         for(int i=0;i<s.size();i++){
 7             if(pos[s[i]]==-1 || pos[s[i]]<left){
 8                 curRes++;              
 9                 pos[s[i]] = i;
10             }
11             else{
12                 curRes = curRes-(pos[s[i]]-left);  //当前长度需要更新,减去left右移的距离
13                 left = pos[s[i]]+1;  
14                 pos[s[i]] = i;               
15             }
16             res = curRes>res?curRes:res;
17         }
18         return res;
19     }
20 };

 

 
posted @ 2018-09-22 00:26  yuchi328  阅读(102)  评论(0)    收藏  举报