Simple Java Solution using HashMap


  • 1
    A
    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            if (s == null || s.isEmpty()){
                return 0;
            }
            if (s.length() == 1){
                return 1;
            }
            int max = 0;
            int start = 0;
            int i = 0;
            HashMap<Character,Integer> hm = new HashMap<Character,Integer>();
            for (i = 0; i < s.length(); i++){
                if (!hm.containsKey(s.charAt(i))){
                    hm.put(s.charAt(i), i);
                }
                else {
                    if ((i - start) > max){
                        max = i - start;
                    }
                    if (hm.get(s.charAt(i)) >= start){
                        start = hm.get(s.charAt(i)) + 1;
                    }
                    hm.put(s.charAt(i),i);
                }
            }
            if( i - start > max){
                max = i - start;
            }
            return max;
        }
    }

Log in to reply
 

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