zoukankan      html  css  js  c++  java
  • 【leetcode刷题笔记】3. 无重复字符的最长子串

    链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/submissions/

    这题主要就是一个滑动窗口。思路马上能想到,但是各种边界条件想明白比较麻烦。

    看了答案后简化版的代码:

    class Solution {
        public int lengthOfLongestSubstring(String s) {
            int endIndex = 0;
            int maxLength = 0;
            Set<Character> existCharSet = new HashSet<>();
            for (int startIndex = 0; startIndex < s.length(); startIndex++) {
                if (startIndex != 0) {
                    existCharSet.remove(s.charAt(startIndex - 1));
                }
                while (!existCharSet.contains(s.charAt(endIndex))) {
                    existCharSet.add(s.charAt(endIndex));
                    endIndex++;
                    if (endIndex == s.length()) {
                        break;
                    }
                }
                maxLength = Math.max(maxLength, endIndex - startIndex);
                if (endIndex == s.length()) {
                    break;
                }
            }
    
            return maxLength;
        }
    }
  • 相关阅读:
    买不到的数目
    逆波兰表达式
    颠倒的价牌
    排它平方数
    寒假作业
    搭积木
    网友年龄
    九宫重排
    格子刷油漆
    高僧斗法
  • 原文地址:https://www.cnblogs.com/funbing/p/14260088.html
Copyright © 2011-2022 走看看