码迷,mamicode.com
首页 > 其他好文 > 详细

3. Longest Substring Without Repeating Characters

时间:2015-04-15 21:12:09      阅读:125      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!