Share my java solution


  • 7
    X
    import java.util.Hashtable;
    public class Solution {
        public int lengthOfLongestSubstring(String s) {
           Hashtable hash=new Hashtable();
           int length=s.length();
           int max=0;
           int availablefrom=0;
           for(int i=0;i<length;i++){
        	   if(hash.containsKey(s.charAt(i))){
        		   int last=(Integer) hash.get(s.charAt(i));
        		   availablefrom=Math.max(availablefrom, last+1);
        	   }
        	   max=Math.max(max, i-availablefrom+1);
        	   hash.put(s.charAt(i),i);   	   
           }
           return max;
        }
    }

  • 0
    A
    This post is deleted!

  • 0
    A

    could u please explain the basic idea of it? thanks


  • 0
    X

    hashtable: key = character, value = that character's largest occurrence index

    int last = the largest index where has the same character (before current index i)

    int available-from = the next index from where latest duplication ends (before current index i)

    then the possible substring is located between available-from and i

    update max if needed
    and update hashtable


Log in to reply
 

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