首页 > 其他 > 详细

3. Longest Substring Without Repeating Characters

时间:2015-04-15 21:12:05      阅读:219      评论:0      收藏:0      [点我收藏+]

题目:

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

链接: http://leetcode.com/problems/longest-substring-without-repeating-characters/

题解:

Sliding Window,每次在HashMap里放入当前字符的index i。 要注意start何时更新。 比如abba这种情况。 Time Complexity - O(n),Space Complexity - O(n)

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

 

3. Longest Substring Without Repeating Characters

原文:http://www.cnblogs.com/yrbbest/p/4429769.html

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