Longest Substring Without Repeating Characters(Java)


  • 0
    J

    My code stuck at the last trial(981/982 ) because it exceeded the time limit. But I don't know how to improve it.
    Can somebody tell me which part of the code occupies the most of the complexity?

    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            int len = s.length();
            char A[] = new char[len];
            int j = 0;
            int k,t;
            int maxlen = 0;
            while(j < len){
                char temp = s.charAt(j);
                String B = new String(A);
                k = B.indexOf(temp);
                if(k == -1){//new char not in A
                    A[j] = temp;
                    j++;
                    if(j == len && (j > maxlen)){
                        maxlen = j;
                    }
                }
                else{//new char is in A
                    if(j > maxlen){
                        maxlen = j;
                    }
                    s = s.substring(k+1, len);
                    j = 0;
                    len = s.length();
                    A = new char[len];
                }
            }
        return maxlen;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.