zoukankan      html  css  js  c++  java
  • Leetcode 3 Longest Substring Without Repeating Characters. (最长无重复字符子串) (滑动窗口, 双指针)


    Leetcode 3

    问题描述

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

    例子

    Example 1:
    Input: "abcabcbb"
    Output: 3 
    Explanation: The answer is "abc", with the length of 3. 
    
    Example 2:
    Input: "bbbbb"
    Output: 1
    Explanation: The answer is "b", with the length of 1.
    
    Example 3:
    Input: "pwwkew"
    Output: 3
    Explanation: 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.
    

    方法一

      保留一个将字符串中的字符存储为键并将其位置存储为值的hashmap,并保留两个定义最大子字符串的指针。移动右指针以浏览字符串,同时更新hashmap。如果字符已经在hashmap中,则将左指针移到最后找到的相同字符的右边。请注意,两个指针只能向前移动。

    ** Solution Java **
    ** 7ms, 79.25% **
    ** 41.9MB, 5.20% **
    class Solution {
        public int lengthOfLongestSubstring(String s) {
            if (s.length() <= 1) return s.length();
            Map<Character, Integer> map = new HashMap<>();
            int cur = 0, max = 0;
            for (int i = 0; i < s.length(); ++i) {
                if (map.containsKey(s.charAt(i))) {
                    cur = Math.max(cur, map.get(s.charAt(i)) + 1);
                }
                map.put(s.charAt(i), i);
                max = Math.max(max, i - cur + 1);
            }
            return max;
        }
    }
    
    ** Solution Python3 **
    ** 56ms, beats 76.40% **
    ** 13MB, beats 99.49% **
    class Solution:
        def lengthOfLongestSubstring(self, s) :
            cur = maxLength = 0
            usedChar = {}
            for index, char in enumerate(s) :
                if char in usedChar and cur <= usedChar[char]:
                    cur = usedChar[char] + 1
                else:
                    maxLength = max(maxLength, index - cur + 1)
                usedChar[char] = index
            return maxLength
    

    方法二

    ** Solution Java **
    ** 3ms, beats 93.80% **
    ** 39.1MB, beats 21.47% **
    class Solution {
        public int lengthOfLongestSubstring(String s) {
            if (s.length() <= 1) return s.length();
            int[] map = new int[128];
            int ans = 0;
            Arrays.fill(map, -1);
            for (int i = 0, j = 0; j < s.length(); ++j) {
                if (map[s.charAt(j)] >= 0)
                    i = Math.max(i, map[s.charAt(j)] + 1);
                ans = Math.max(ans, j - i + 1);
                map[s.charAt(j)] = j;
            }
            return ans;
        }
    }
    
  • 相关阅读:
    判断有无网络
    Listview的OnScrollListener的滑动监听实现分页加载
    第三方 XListview 上拉加载、下拉刷新、分页加载和Gson解析
    Gson解析数据
    百度地图实现普通地图、定位、周边搜索功能
    Viewpager实现网络图片的轮播
    英语wacche腕表
    caement Archaic spelling of cement
    水泥caement单词
    英语caement水泥
  • 原文地址:https://www.cnblogs.com/willwuss/p/12275316.html
Copyright © 2011-2022 走看看