My Java solution easy to understand with O(N) complex


  • 0
    L
    public class Solution {
        public static int lengthOfLongestSubstring(String s) {
            if(s.length() <= 0) return 0;
            int[] lengthNum = new int[s.length()];
            Map<Character, Integer> index = new HashMap<>();
            lengthNum[0] = 1;
            index.put(s.charAt(0), 0);
            int max = 0;
            for(int i = 1; i < s.length(); i++) {
                if(!index.containsKey(s.charAt(i))) {
                    lengthNum[i] = lengthNum[i-1] + 1;
                }
                else if(i - index.get(s.charAt(i)) <= lengthNum[i-1])  {
                    lengthNum[i] = i - index.get(s.charAt(i));
                }
                else{
                    lengthNum[i] = lengthNum[i-1] + 1;
                }
                index.put(s.charAt(i), i);
            }
            for(int i = 0; i < s.length(); i++) {
                max = Math.max(max, lengthNum[i]);
            }
            return max;
        }
    }
    

Log in to reply
 

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