美文网首页
3. Longest Substring Without Rep

3. Longest Substring Without Rep

作者: gpfworld | 来源:发表于2018-11-27 16:56 被阅读0次

题目描述:

https://leetcode.com/problems/longest-substring-without-repeating-characters/

解决方法:

https://leetcode.com/problems/longest-substring-without-repeating-characters/solution/

mycode(c++):

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        unordered_map<char,int> map ;
        int ans = 0;
        int n = s.length();
        for (int i = 0,j = 0 ; j < n ; j++){
            if( map.find( s.at(j) )!= map.end()){
                i = max(map[s.at(j)],i);
            }
            ans = max(ans,j-i+1);
            map.erase(s.at(j));
            map.insert(make_pair(s.at(j),j+1));
        }
        return ans;
    }
};

心得:

暴力搜索方案,会出现很多不必要的重复搜索。
滑动窗口,减少了重复搜索,因为在第j个位置的字符串已经重复的情况下,就没必要接着搜索j+1的位置,原因在于寻找的是连续的子串
滑动窗口优化:在之前的基础上,记录出现重复字符的位置,之前的位置就没必要搜索,所以直接跳过就可以
使用自定义hashmap:如果字符集简单的情况下,就可以使用数组,没必要使用库函数的map,可以自定义,这样效率更高

相关文章

网友评论

      本文标题:3. Longest Substring Without Rep

      本文链接:https://www.haomeiwen.com/subject/zwtnqqtx.html