Sunday, February 9, 2014

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.

Solution:
Iterate through the string, and check if the current char is existed in the longest substring. If it exists, cut off the longest substring from the next char of the already existed char.


public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int longest = 0;
        char[] c = s.toCharArray();
        String str = new String();
        for(int i = 0; i < c.length; i++){
            int pos = str.indexOf(c[i]);
            if(pos > -1){  // exist
                if(str.length() > longest) longest = str.length();
                str = str.substring(pos+1) + c[i];
            }
            else str += c[i];
        }
        if(str.length() > longest) longest = str.length(); 
        return longest;
    }
}

No comments:

Post a Comment