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

Longest Substring Without Repeating Characters

时间:2015-03-02 23:48:30      阅读:157      评论: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.

 

只扫描一遍字符串s的解法,即时间复杂度为O(n),代码如下:

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int start = 0;
        Map<Character,Integer> map = new HashMap<Character,Integer>();
        int max_length = 0;
        int size = s.length();//字符串长度
        for(int i=0;i<size;i++) {
            char c = s.charAt(i);
            if(map.containsKey(c)) {
                int sub_length = i-start;
                max_length = sub_length>max_length?sub_length:max_length;
                int index = map.get(s.charAt(i));//之前出现过c的位置
                //将start到index所有字符从map中删除
                for(int j=start;j<=index;j++) {
                    map.remove(s.charAt(j));
                }
                map.put(c,i);
                start = index+1;//更新start
            }
            else {
                map.put(c,i);
                if(i==size-1) max_length = map.size()>max_length?map.size():max_length;
            }
        }
        return max_length;
    }
}

问题关键是如何在常量时间内判断当前字符是否在字串中出现过,必须用到一个hashmap。如果直接使用String 的contains方法会导致效率过低,limit time exceed。

Longest Substring Without Repeating Characters

标签:

原文地址:http://www.cnblogs.com/mrpod2g/p/4309959.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!