zoukankan      html  css  js  c++  java
  • Leecode no.3 无重复字符的最长子串

    package leecode;

    import java.util.HashMap;
    import java.util.Map;

    /**
    * 3. 无重复字符的最长子串
    * 给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
    *
    *
    * @author Tang
    * @date 2021/12/7
    */
    public class LengthOfLongestSubstring {

    /**
    * 滑动窗口方法
    *
    *
    * @param s
    * @return
    */
    public int lengthOfLongestSubstring(String s) {
    char[] all = s.toCharArray();

    //初始化窗口
    Map<Character, Integer> window = new HashMap<>();

    //窗口左右指针
    int left = 0;
    int right = 0;

    //当前窗口中不同元素的个数
    int valid = 0;

    int result = 0;

    while(right < all.length) {
    char c = all[right];
    right++;

    //窗口中没有和c重复的值
    if(!window.containsKey(c)) {
    window.put(c, 1);
    valid++;

    //更新result
    result = Math.max(result, valid);
    continue;
    }

    //如果有重复元素则窗口左缩
    //左缩到把c重复元素干掉
    while(window.containsKey(c)) {
    char d = all[left];
    left++;
    window.remove(d);
    valid--;
    }

    //最后把这个c加入窗口
    window.put(c, 1);
    valid++;
    }
    return Math.max(valid, result);
    }

    // /**
    // * 循环遍历方法
    // * 循环元素,判断以每个元素开头的最长子串,更新result
    // * @param s
    // * @return
    // */
    // public int lengthOfLongestSubstring(String s) {
    // if(s.equals(" ")) {
    // return 1;
    // }
    //
    //
    // char[] all = s.toCharArray();
    //
    // int result = 0;
    //
    // Map<Character, Integer> map = null;
    // for(int i = 0; i < all.length; i++) {
    // map = new HashMap<>();
    //
    // for(int j = i; j < all.length; j++) {
    // if(map.containsKey(all[j])) {
    // break;
    // }
    // map.put(all[j], 1);
    // result = Math.max(result, map.size());
    // }
    //
    //
    // }
    //
    // return result;
    //
    // }

    public static void main(String[] args) {


    }

    }
  • 相关阅读:
    table拖动列宽
    解决 wm_concat函数 长度不够问题
    「Luogu」[JSOI2007]字符加密 解题报告
    Markdown数学符号
    「P5004」专心OI
    「CF242E」XOR on Segment 解题报告
    「CF86D」Powerful array 解题报告
    「USACO08JAN」电话线Telephone Lines 解题报告
    「Luogu P2015」二叉苹果树 解题报告
    「Luogu P3866」[TJOI2009]战争游戏 解题报告
  • 原文地址:https://www.cnblogs.com/ttaall/p/15656670.html
Copyright © 2011-2022 走看看