Leetcode: Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

分析:该题目跟Minimum Substring Window 有相通之处,两个题目都是求一个特殊的window长度,Minimum Substring Window中求的是一个包含某string所有字符的最小window,而这道题是求一个所有字符都不同的最大window,两者都可以用two pointers的方法解。

此题两个关键点:(1) 如何扩展window (2)遇到重复字符时如何缩小window。

我们可以用一个数组保存已经出现的字符的index,如果字符未出现则为-1;当遇到重复字符时,我们只需将指向window开始的指针移动到第一个重复字符出现的位置之后即可。

时间复杂度为O(n),空间复杂度O(n)。代码如下:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        vector<int> pos(128, -1);
        
        int start = 0, end = 0;
        int maxLength = 0;
        
        for(; end < s.length(); end++){
            if(pos[s[end]] >= start){
                start = pos[s[end]] + 1;
            }else{
                maxLength = max(maxLength, end-start+1);
            }
            pos[s[end]] = end;
        }
        
        return maxLength;
    }
};

 

posted on 2014-12-08 19:39  Ryan-Xing  阅读(129)  评论(0编辑  收藏  举报