zoukankan      html  css  js  c++  java
  • 3. Longest Substring Without Repeating Characters 最长子串,无重复字符

    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

    .
    思路:知道要判断value > 1,但是答案的思路是:charAt(end)有重复就往前移,寻找下一个没有被重复的字母

    counter是需要调节的,怎么调节需要动脑子。也不是一个一模一样的模板走天下:
    counter表示的是无效的字母个数,但是因为之前统计过了,这里就一直减少。是为了维持两者在同一窗口内吧

    d = Math.max(d, end - begin);
    //d是在while循环之后更新,可能因为begin要尽量往前移,让结果尽量短?

     
    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            Map<Character, Integer> map = new HashMap<>();
            int begin = 0, end = 0, counter = 0, d = 0;
    
            while (end < s.length()) {
                // > 0 means repeating character
                //if(map[s.charAt(end++)]-- > 0) counter++;
                char c = s.charAt(end);
                map.put(c, map.getOrDefault(c, 0) + 1);
                if(map.get(c) > 1) counter++;
                end++;
                
                while (counter > 0) {
                    //if (map[s.charAt(begin++)]-- > 1) counter--;
                    char charTemp = s.charAt(begin);
                    if (map.get(charTemp) > 1) counter--;
                    map.put(charTemp, map.get(charTemp)-1);
                    begin++;
    
                    //d = Math.max(d, end - begin);
                }
                //d = Math.max(d, end - begin);
                if (end - begin > d) 
                    d = end - begin;
            }
            return d;
        }
    }
    View Code
    
    
    


  • 相关阅读:
    qt QTimer 计时器
    qt DateTime 计算时间
    c++ win32 关机 注销 重启
    uniapp 修改meta:viewport
    初次使用 VUX
    移动端web app自适应布局探索与总结
    前端js模版 预编译工具Tmod js使用入门
    谷歌 Uncaught SecurityError: Failed to execute 'replaceState' on 'History 错误
    H5 前端页面适配响应式
    微信video标签全屏无法退出bug 本文系转载
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13408635.html
Copyright © 2011-2022 走看看