美文网首页
无重复字符的最长子串

无重复字符的最长子串

作者: 二进制的二哈 | 来源:发表于2019-11-25 11:51 被阅读0次

    题目来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
    给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

    示例 1:

    输入: "abcabcbb"
    输出: 3 
    解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
    示例 2:
    
    输入: "bbbbb"
    输出: 1
    解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
    示例 3:
    
    输入: "pwwkew"
    输出: 3
    解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
         请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
    

    Java代码:

    class Solution {
        public int lengthOfLongestSubstring(String s) {
            if(s.length() <= 1)
                return s.length();
    
            int maxLen = 0;
            int curLen = 0;
            int startIndex = 0;
            Map<Character,Integer> map = new HashMap<>();
    
            for(int i = 0;i<s.length();i++){
                char c = s.charAt(i);
                Integer index = map.get(c);
                if(index != null){
                    if(index >= startIndex)
                        startIndex = index;
                    //说明重复了
                    curLen = i - startIndex ;
                }else{
                    //没有重复
                    curLen++;
                }
                if(curLen > maxLen)
                        maxLen = curLen;
                map.put(c,i);
            }
            return maxLen;
            
        }
    }
    

    Python代码:

    class Solution:
        def lengthOfLongestSubstring(self, s: str) -> int:
            length = len(s)
            if length <= 1 :
                return length
            maxLen=curLen=startIndex = 0
            dic = {}
            for index,c in enumerate(s) :
                if c in dic.keys():
                    if startIndex < dic[c] :
                        startIndex = dic[c]
                    curLen = index - startIndex 
                else:
                    curLen = curLen + 1
                dic[c] = index
                if curLen > maxLen:
                    maxLen = curLen
    
            return maxLen
    

    相关文章

      网友评论

          本文标题:无重复字符的最长子串

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