3. Longest Substring Without Repeating Characters

Problem:

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.

---

Idea:

boolean array to store the visited chars

When find a repeated character (e.g. index == j)

  - the current substring (excluding the repeated character of course) is a potential maximum, so update the maximum if necessary.

  - the repeated character must have appeared before at an index i, where i is less than j.

  - start to look for the next substring with head which starts exactly at index  i+1.

common mistake of not updating the maximum after the main loop

T: O(n).

---

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        
        int n = s.length();
        int i=0, j=0;
        int maxlen = 0;
        boolean[] exist = new boolean[256];
        
        while(j < n){
            
            int val = s.charAt(j);
            
            if(exist[val]){
                // update maxlen
                maxlen = Math.max(maxlen, j-i);
                // clear the exist
                while(s.charAt(i) != val){
                    exist[s.charAt(i)] = false;
                    i++;
                }
                // move to a new start
                i++;
                j++;
            }else{
                exist[val] = true;
                j++;
            }
        }
        
        // update the maxlen!
        maxlen = Math.max(maxlen, n-i);
        
        return maxlen;
        
    }
}

 

posted @ 2013-08-29 12:16  LEDYC  阅读(184)  评论(0)    收藏  举报