首页 > 代码库 > 3. Longest Substring Without Repeating Characters
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。