6/06/2014

106. Longest Substring Without Repeating Characters

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

没有评论:

发表评论