Finally work it out~ (using java)


  • 3
    M
    public int lengthOfLongestSubstring(String s) {
        if(s.length() == 1) return 1;
        int max = 0;
        int begin = 0;
        int sublength = 0;
        HashMap<Character,Integer> map = new HashMap<Character,Integer>();
        
        for(int i = 0; i < s.length(); i++){
           if(map.containsKey(s.charAt(i))){
                sublength  = i - begin;
                max = Math.max(sublength, max);
               begin = Math.max(begin, map.get(s.charAt(i)) + 1) ;
            }
            map.put(s.charAt(i),i);
            if(i == s.length()-1){
                max = Math.max(i - begin + 1, max);
            }
        }
        return max;
    }

  • 0
    R

    public int lengthOfLongestSubstring(String s) {
    int result = 0;
    String temp = "";
    for(int i=0; i<s.length(); i++){
    if(temp.contains(""+s.charAt(i))){
    i = i - temp.length();
    if(temp.length()>result) result = temp.length();
    temp = "";
    }
    else{
    temp = temp + s.charAt(i);
    if(temp.length()>result) result = temp.length();
    }
    }
    return result;
    }


Log in to reply
 

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