4ms java solution


  • 6
    A
    public class Solution {
            public int lengthOfLongestSubstring(String s) {
                char[] arr = s.toCharArray();
                int max = 0, cur = 0, start = 0;
                int[] map = new int[255];
                for(int i = 0; i < arr.length; i++){
                    char c = arr[i];
                    if(map[c] == 0){
                        //first time appears
                        map[c] = i+1; //mark the position
                        cur++;  //length
                        if(cur > max) max = cur;
                    }else{
                        int end = map[c]-1; //real index of prev appearance of current char
                        for(int j = start; j < end; j++){
                            map[arr[j]] = 0; //mark off previous letters as never appeared
                        }
                        start = end+1; //start of the new substring
                        map[arr[i]] = i+1; //update current position
                        cur = i-end; //update length of current substring
                    }
                }
                return max;
            }
        }

Log in to reply
 

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