• 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) {


    }

    }
  • 相关阅读:
    redis主从架构
    redis持久化
    git 首次push失败
    Java8 CompletableFuture
    Mac Item2自动远程连接服务器
    Java8 日期和时间类
    【LeetCode】31. 下一个排列
    【LeetCode】30. 串联所有单词的子串
    【LeetCode】29. 两数相除
    【LeetCode】28. 实现 strStr()
  • 原文地址:https://www.cnblogs.com/ttaall/p/15656670.html
Copyright © 2020-2023  润新知