LeetCode 3 – Longest Substring Without Repeated Characters

Posted on December 21, 2013

Last updated on December 21, 2013

Solution to LeetCode Longest Substring Without Repeated Characters problem.

The idea is that last[i] is the last occurence of the letter (with ascii code) i, or \(-1\) if it hasn’t appeared yet. ‘cur_len’ is the length of the current sequence we are considering.

First, process the first character and setup all the variables accordingly. Then, for every other character:

public int lengthOfLongestSubstring(String s) {
  if(s.length() == 0) return 0;
  char[] C = s.toCharArray();

  int[] last = new int[150];
  for(int i = 0; i < last.length; i++) last[i] = -1;

  last[C[0]] = 0;

  int max_len = 1;
  int cur_len = 1;

  for(int i = 1; i < C.length; i++){
    int lastIndex = last[C[i]];

    if(lastIndex == -1 || i - lastIndex > cur_len){
      cur_len++;
    }
    else{
      max_len = Math.max(max_len, cur_len);
      cur_len = i - lastIndex;
    }

    last[C[i]] = i;
  }
  return Math.max(max_len, cur_len);
}
Longest Substring Without Repeated Characters
Markdown SHA1: 8eb6e4dc13ae384b09d2f670db27d4a8b4e0bb69