Java solution, beats 95%


  • 0

    beats 95%

    public class WordDistance {
        HashMap<String, ArrayList<Integer>> map = new HashMap<String, ArrayList<Integer>>();
    
        public WordDistance(String[] words) {
            for(int i = 0; i < words.length; i++){
                if(!map.containsKey(words[i])) {
                    map.put(words[i], new ArrayList<Integer>());
                }
                
                map.get(words[i]).add(i);
            }
        }
    
        public int shortest(String word1, String word2) {
            ArrayList<Integer> p1 = map.get(word1);
            ArrayList<Integer> p2 = map.get(word2);
            
            int min = Integer.MAX_VALUE;
            int i1 = 0;
            int i2 = 0;
            while(i1 < p1.size() && i2 < p2.size()) {
                int diff = Math.abs(p1.get(i1) - p2.get(i2));
                if(diff < min) {
                    min = diff;
                }
                
                if(p1.get(i1) < p2.get(i2)) {
                    i1++;
                } else if(i2 < p2.size()){
                    i2++;
                }
            }
            return min;
        }
    }
    
    // Your WordDistance object will be instantiated and called as such:
    // WordDistance wordDistance = new WordDistance(words);
    // wordDistance.shortest("word1", "word2");
    // wordDistance.shortest("anotherWord1", "anotherWord2");
    

Log in to reply
 

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