Problem:
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.
Intuition:
这个题目总体来说就是运用了滑动窗口的思想。如果算法题中一旦出现了固定长度求最值或者提供限制条件求最大长度的时候就应该有使用这个算法的意识。
如果是固定长度求最值的问题(譬如求数组中连续k个元素最大的和),那么我们就先指定两个下标i,j(j=i+k-1),对k个元素长的子数组进行求和,然后每次移动i的时候,j也往相同方向移动一格,这样就可以在O(n)的时间复杂度内得到答案。
如果是限制条件求最大长度的问题(譬如本题),只需在每次移动下标的时候用set对新元素进行检查,如果成功就把j往后移,继续扩展数组长度。否则将i往后移看是否能规避冲突。
给一个滑动窗口算法相关的讨论链接:https://www.zhihu.com/question/314669016
以后如果有时间会在博客中讨论这个话题。
Solution:
1 | public static int lengthOfLongestSubstringSolution(String s){ |