Longest Substring Without Repeating Characters

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.

 

从左往右扫描,当遇到重复字母时,以上一个重复字母的index +1,作为新的搜索起始位置。

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int[] count = new int[26];
  
        resetCount(count);
        
        int sLength = s.length();
        int maxL = 0;
        int start = 0;
        for(int i = 0; i < sLength; i++){
            int index = s.charAt(i) - 97;
            
            if(count[index] >= 0){
                if(i - start > maxL){
                    maxL = i - start;
                }
                // need to backtrack !!!
                i = count[index];
                start = i + 1;
                resetCount(count);
                continue;
            }
            
            count[index] = i;
            
        }
        
        // if last round have no repeating characters, we should check
        if(maxL < sLength - start){
            maxL = sLength - start;
        }
        return maxL;
    }
    
    public void resetCount(int[] count){
        for(int i = 0; i < 26; i ++){
            count[i] = -1;   
        }
    }
}

 

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s == null)
            return 0;
            
        char[] myChar = s.toCharArray();
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int maxLen = 0;
        for(int i = 0 ; i < myChar.length; i++){
            if(map.containsKey(myChar[i])){
                maxLen = map.size() > maxLen ? map.size() : maxLen;
                i = map.get(myChar[i]);
                map.clear();
            }else{
                map.put(myChar[i], i);
            }
        }
        maxLen = map.size() > maxLen ? map.size() : maxLen;
        return maxLen;
        
    }
}

 

 

posted @ 2014-02-17 07:31  Razer.Lu  阅读(286)  评论(0编辑  收藏  举报