zoukankan      html  css  js  c++  java
  • 蜗牛慢慢爬 LeetCode 3. Longest Substring Without Repeating Characters [Difficulty: Medium]

    题目

    Given a string, find the length of the longest substring without repeating characters.

    Examples:
    Given "abcabcbb", the answer is "abc", which the length is 3.
    Given "bbbbb", the answer is "b", with the length of 1.
    Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

    翻译

    给定一个字符串,找到没有重复字符的最长子串的长度。
    例子:
    给定“abcabcbb”,答案是“abc”,长度为3。
    给定“bbbbb”,答案是“b”,长度为1。
    给定“pwwkew”,答案是“wke”,长度为3.请注意,答案必须是子字符串,“pwke”是子序列而不是子字符串。

    Hints

    Related Topics: Hash Table, Two Pointers, String
    利用哈希表来存储字符的位置
    计算以字符s结尾的子串的长度 需要一个指针来遍历string来获取每个字符s 还需要一个指针来表示当前以s结尾的子串的头部的位置
    遇到之前出现过的字符时 表示上一个子串已经包含了s 需要重新计算头部 于是移动头部指针
    参考

    代码

    Java

    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            if (s.length()==0)  return 0;
            int max = 0;
            int start = 0;//表示现在用来计算最长子串的头的位置
            Map<Character, Integer> mymap = new HashMap<>();//通过哈希表来存储现在某个字符出现的位置
            for(int i=0;i<s.length();i++){
                if(mymap.containsKey(s.charAt(i))){//现在这个字符在之前出现过
                    start = Math.max(start,mymap.get(s.charAt(i)+1);//需要把头移动到这个字符后面(头原来在上一个这个字符前面
                }
                mymap.put(s.charAt(i),i);//更新字符的位置
                max = Math.max(max,i-start+1);//更新最长字串长度
            }
            return max;
        }
    }
    
    

    Python

    class Solution(object):
        def lengthOfLongestSubstring(self, s):
            """
            :type s: str
            :rtype: int
            """
            start = maxlen = 0
            mymap={}
            for i in range(len(s)):
                if s[i] in mymap:
                    start = max(start,mymap[s[i]]+1)
               
                maxlen = max(maxlen,i-start+1)
                mymap[s[i]] = i
            return maxlen
            
    
  • 相关阅读:
    Codevs堆练习
    codevs 3110 二叉堆练习3
    浅谈堆
    codevs 2924 数独挑战
    搜索技巧——持续更新
    2144 砝码称重 2
    codevs 2928 你缺什么
    codevs 2594 解药还是毒药
    codevs 2147 数星星
    判断素数
  • 原文地址:https://www.cnblogs.com/cookielbsc/p/7428609.html
Copyright © 2011-2022 走看看