leetcode无重复字符的最长子串

时间:2022-07-22
本文章向大家介绍leetcode无重复字符的最长子串,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

给定一个字符串,找出不含有重复字符的最长子串的长度。

输入: "abcabcbb"
输出: 3 
解释: 无重复字符的最长子串是 "abc",其长度为 3。

python

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        i = 0;j = 0;ans = 0
        maps = {}
        for j in range(len(s)):
            if maps.__contains__(s[j]):
                i = max(i,maps.get(s[j]))
            ans = max(ans,j-i+1)
            maps[s[j]] = j+1
        return ans

java

class Solution {
   public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        int i = 0,j = 0;
        int ans = 0;
        HashMap<Character,Integer> map = new HashMap<>();
        for(i=0,j=0;j<n;j++){
            if(map.containsKey(s.charAt(j))){
                i = Math.max(map.get(s.charAt(j)),i);
            }
            ans = Math.max(j-i+1,ans);
            map.put(s.charAt(j),j+1);
        }
        return ans;
    }
}