Leetcode–Longest Substring Without Repeating Characters

The 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.

Notes:

  1. Check for repeating characters we can use an int or bool array of 256, no need for hash set.
  2. Remember to update the max length again when get out of while loop.

Java Solution:

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s.length()<=1)return s.length();
        
        int start = 0;
        int end = start;
        int[] occur = new int[256];
        Arrays.fill(occur, 0);
        int maxLen = 0;
        while(start < s.length() && end < s.length()){
            if(occur[s.charAt(end)]==0){
                occur[s.charAt(end)]=1;
                end++;
            }
            else{
                maxLen = Math.max(maxLen,end-start);
                occur[s.charAt(start)]--;
                start++;
            }
        }
        maxLen = Math.max(maxLen,end-start);
        return maxLen;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s