首页 > 其他 > 详细

3. Longest Substring Without Repeating Characters

时间:2016-10-10 07:41:46      阅读:262      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/Machelsky/p/5944451.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!