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

Longest Substring Without Repeating Characters

时间:2014-07-29 14:28:48      阅读:218      评论: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.

public class Solution {
   public static int lengthOfLongestSubstring(String s) {
        int count=0;
        int start=0;
        int max=0;
        Map<Character,Integer> map=new HashMap<Character,Integer>();
        for(int i=0;i<s.length();i++){
            if(map.containsKey(s.charAt(i))!=true){
                count++;
                map.put(s.charAt(i),i);
            }
            else{
                if(max<count) max=count; 
                if(start<map.get(s.charAt(i))) start=map.get(s.charAt(i));
                count=i-start;
                map.put(s.charAt(i), i);
            }
        }
        if(max<count) max=count; 
        return max;
    }
}
思路:O(n)解法,遍历字符串,逐个添加,用HashMap检查是否有重复字符,更新长度和统计的起始坐标。

下面这个写法代码更简洁一点。

public class Solution {
   public static int lengthOfLongestSubstring(String s) {
        int start=0;
        int max=0;
        Map<Character,Integer> map=new HashMap<Character,Integer>();
        for(int i=0;i<s.length();i++){
            if(map.containsKey(s.charAt(i))==true){
                if(start<=map.get(s.charAt(i))) 
                    start=map.get(s.charAt(i))+1;//update start index
            }
            map.put(s.charAt(i), i);
            if(max<(i-start+1)) max=i-start+1;//update max
        }
        return max;
    }
}


Longest Substring Without Repeating Characters,布布扣,bubuko.com

Longest Substring Without Repeating Characters

标签:数据结构   算法   学习   

原文地址:http://blog.csdn.net/dutsoft/article/details/38237205

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