3. Longest Substring Without Repeating Characters
Posted Machelsky
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3. Longest Substring Without Repeating Characters相关的知识,希望对你有一定的参考价值。
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, 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.
思路:滑动窗口。用map记录char和index,如果碰到相同的char,则将窗口向右滑动。注意 initial=Math.max(res.get(s.charAt(i))+1,initial);,滑动的时候注意如果碰到的重复字母在窗口的左边则不滑动。
public class Solution { public int lengthOfLongestSubstring(String s) { if(s.length()==0){ return 0; } if(s.length()==1){ return 1; } int longest=0; int initial=0; Map<Character,Integer> res=new HashMap<>(); for(int i=0;i<s.length();i++){ if(res.containsKey(s.charAt(i))){ initial=Math.max(res.get(s.charAt(i))+1,initial); } res.put(s.charAt(i),i); longest=Math.max(longest,i-initial+1); } return longest; } }
以上是关于3. Longest Substring Without Repeating Characters的主要内容,如果未能解决你的问题,请参考以下文章
longest-substring-with-at-least-k-repeating-characters
LeetCode 395. Longest Substring with At Least K Repeating Characters
395. Longest Substring with At Least K Repeating Characters
3. Longest Substring Without Repeating Characters
Leetcode: Longest Substring with At Least K Repeating Characters