Simple java solution with hashmap


  • 0
    S
    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            int max = 0;
            int left = 0, right = 0;
            int len = s.length();
            
            if(len == 0 || len == 1) return len;
            
            Map<Character, Integer> map = new HashMap<>();
            map.put(s.charAt(0), 0);
            
            for(int i=1; i<len; i++) {
                char c = s.charAt(i);
                right = i;
                if(map.containsKey(c)) {
                    int index = map.get(c);
                    if(index >= left) {
                        left = index+1;
                    }
                }
                map.put(c, i);
                max = Math.max(max, right-left+1);
            }
            
            return max;
        }
    }

  • 0
    X

    in the if ,map should renew???if don't ,it will wrong.for example abcabcd


  • 0
    S

    Hi my friend, you can check for the statement of "if(index >= left)" the judgement has been set here to avoid your situation


Log in to reply
 

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