[Leetcode 3] 最长不重复子串 Longest substring without repeating 滑动窗口

时间:2023-03-08 21:09:19

【题目】

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.
【思路】
  滑动窗口Sliding Window 【代码】

public class Solution {
  public int lengthOfLongestSubstring(String s) {
  int len=s.length();
  int ans=0;int j=0;
  Map<Character,Integer> map=new HashMap<>();
  for(int i=0;i<len;i++){
    if(map.containsKey(s.charAt(i))){
      j=Math.max(j,map.get(s.charAt(i)));
    }
    ans=Math.max(ans,i-j+1);
    map.put(s.charAt(i),i+1);
  }
  return ans;
 }
}