[LeetCode] 3. Longest Substring Without Repeating Characters

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

Example 1:

Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:

Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

Example 4:

Input: s = ""
Output: 0

Constraints:

  • 0 <= s.length <= 5 * 104
  • s consists of English letters, digits, symbols and spaces.

最长无重复字符的子串。

题意是给一个 input 字符串,请输出其最长的,没有重复字符的子串的长度。这是two pointer追击型指针/sliding window的基础题

思路是用一个 hashmap 或者 hashset 以及两个指针 i 和 j,其中 i 指针在左边,j 指针在右边,j 指针每次看当前遍历到的 character 是否在 hashset 中出现过,此时有两种情况

  • 如果没出现过则将当前这个字符串加入 hashset 并且 j++,同时每次更新一下此时此刻两个指针之间的距离 res,这就是满足题意的子串的长度
  • 如果出现过则将 i 指针指向的字母从 hashset 中删除并且 i++

时间O(n)

空间O(n) - hashset

Java实现

 1 class Solution {
 2     public int lengthOfLongestSubstring(String s) {
 3         int i = 0;
 4         int j = 0;
 5         int res = 0;
 6         HashSet<Character> set = new HashSet<>();
 7         while (j < s.length()) {
 8             if (!set.contains(s.charAt(j))) {
 9                 set.add(s.charAt(j));
10                 j++;
11                 res = Math.max(res, j - i);
12             } else {
13                 set.remove(s.charAt(i));
14                 i++;
15             }
16         }
17         return res;
18     }
19 }

JavaScript实现

 1 /**
 2  * @param {string} s
 3  * @return {number}
 4  */
 5 var lengthOfLongestSubstring = function (s) {
 6     let map = {};
 7     let res = 0;
 8     let i = 0;
 9     let j = 0;
10     while (j < s.length) {
11         if (map[s[j]]) {
12             map[s[i]] = false;
13             i++;
14         } else {
15             map[s[j]] = true;
16             res = Math.max(res, j - i + 1);
17             j++;
18         }
19     }
20     return res;
21 };

相关题目

3. Longest Substring Without Repeating Characters

1695. Maximum Erasure Value

sliding window相关题目

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/12190151.html