LeetCode: 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:

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int maxLen = 0;
        if(s.length() == 1) return 1;
        else {
            int l = 0; int r = 0;
            int[] set = new int[256];
            Arrays.fill(set,-1);
            for(int i = 0; i < s.length(); i++){
                int len = 0;
                if(-1 == set[s.charAt(i)] || set[s.charAt(i)] < l){
                    r = i;
                    len = r -l+1;
                    set[s.charAt(i)] = i;
                }else {
                    l = set[s.charAt(i)] + 1;
                    r = i;
                    set[s.charAt(i)] = i;
                }
                maxLen = Math.max(maxLen,len);
            }
            return maxLen;
        }
    }
}

 

posted @ 2014-07-03 22:24  andyqee  阅读(92)  评论(0编辑  收藏  举报