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

你。 提交于 2019-12-22 01:21:28

在这里插入图片描述

leetcode的题解:
https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/solution/wu-zhong-fu-zi-fu-de-zui-chang-zi-chuan-by-leetcod/
在这里插入图片描述
java版:

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length(), ans = 0;
        Map<Character, Integer> map = new HashMap<>(); // current index of character
        // try to extend the range [i, j]
        for (int j = 0, i = 0; j < n; j++) {
            if (map.containsKey(s.charAt(j))) {
                i = Math.max(map.get(s.charAt(j)), i);
            }
            ans = Math.max(ans, j - i + 1);
            map.put(s.charAt(j), j + 1); 	//注:重复key会覆盖value值 
            //System.out.println(map);
        }
        return ans;
    }
}
 map.put(s.charAt(j), j + 1); 

上面这里存的是j+1而不是j,方便i更新值

i = Math.max(map.get(s.charAt(j)), i); //取大的防止i左移

可以改成这样:
在这里插入图片描述

改成C++:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        map<char,int> mymap;
        int ans = 0;
        for(int i = 0, j = 0; j < s.size(); j++)
        {
            if(mymap.count(s[j]) == 1)
            {
                i = max(mymap[s[j]], i);
            }
            ans = max(ans, j - i + 1);
            mymap[s[j]] = j + 1;
        }
        return ans;
    }
};
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        map<char,int> mymap;
        int ans = 0;
        for(int i = 0, j = 0; j < s.size(); j++)
        {
            i = max(mymap[s[j]], i);	//如果mymap里没s[j]这个key,mymap[s[j]] = 0
            ans = max(ans, j - i + 1);
            mymap[s[j]] = j + 1;
        }
        return ans;
    }
};

在这里插入图片描述
在这里插入图片描述

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        vector<int>mymap(256,-1);
        int left = -1;
        int res = 0;
        int len = s.size();
        for(int i = 0; i < len; i++)
        {
            left = max(mymap[s[i]], left);
            mymap[s[i]] = i;
            res = max(res, i - left);
        }
        return res;
    }
};

参考:
leetcode

https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/solution/wu-zhong-fu-zi-fu-de-zui-chang-zi-chuan-by-leetcod/

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!