码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Longest Substring Without Repeating Characters

时间:2014-12-08 21:07:17      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   for   

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(1)。代码如下:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int n = s.length();
        if(n == 0) return 0;
        vector<int> pos(256, -1);
        int win_start = 0, max_width = 0;
        
        for(int win_end = 0; win_end < n; win_end++){
            if(pos[s[win_end]] == -1){//not repeating character
                pos[s[win_end]] = win_end;
                max_width = max(max_width, win_end - win_start +1);
            }else{//repeating character
                for(; win_start < pos[s[win_end]]; win_start++){//eliminate characters from win_start to pos[s[win_end]]
                    pos[s[win_start]] = -1;
                }
                win_start++;
                pos[s[win_end]] = win_end;
            }
        }
        
        return max_width;
    }
};

 

Leetcode: Longest Substring Without Repeating Characters

标签:style   blog   http   io   ar   color   os   sp   for   

原文地址:http://www.cnblogs.com/Kai-Xing/p/4151801.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!