leetcode 3 无重复字符的最长子串

 

 

O(n)time,O(n)space

/*****
动态规划?
维护一个window(i,j)表示i到当前元素j为0~j且包含j元素的最长子串下标(用下标避免不断的插入删除)
维护一个哈希表为当前元素是否出现在当前最长子串中unordered_map<char,insubstr> insubstr用1和0表示;
dp[i]为0~j且包含j元素的最长子串长度(可以直接压缩为一个cur_l变量降低空间复杂度)
***/


class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        
        int ls=s.length();
        if(ls<=1) return s.size();
        
        int res=0;
        unordered_map<char,int>m;
        int left=-1;//left为当前window左边界的前一位
        for(int i=0;i<ls;i++){
            char c=s[i];
            //在left到i(即(left,i])之间c有出现过
            if(m.count(c)&&left<m[c] )left=m[c];
            m[c]=i;
            int cur=i-left;
            res=res>cur?res:cur;
        }
        
        return res;
        
    }
};

 

posted @ 2019-05-23 17:43  Joel_Wang  阅读(237)  评论(0编辑  收藏  举报