[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.

两个指针,采用hash记录出现字母的位置。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        vector<int>hash (300,-1);
        int i,j;
        i=0;
        j=0;
        if(s.size()==0)
            return 0;
        if(s.size()==1)
            return 1;
        int ret=0;
        while(i<=j && j<s.length()){
            if(hash[s[j]]!=-1){
                for(;i<hash[s[j]];++i){
                    hash[s[i]] = -1;
                }
                i = hash[s[j]]+1;
                hash[s[j]]=j;
            }
            else{
                hash[s[j]]=j;
            }
            ret = max(ret,j-i+1);
            ++j;
        }
        return ret;
    }
    
};


阅读更多
个人分类: LeetCode
上一篇[LeetCode]First Missing Positive
下一篇[LeetCode]Longest Substring Without Repeating Characters
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭