|
| 1 | +/** |
| 2 | +* question: http://www.programcreek.com/2014/07/leetcode-shortest-word-distance-ii-java/ |
| 3 | +* |
| 4 | +*/ |
| 5 | + |
| 6 | +functionShortestWordDist(words){ |
| 7 | +this.hashMap={}; |
| 8 | + |
| 9 | +varmap=this.hashMap; |
| 10 | + |
| 11 | +words.forEach(function(word,index){ |
| 12 | +if(wordinmap){ |
| 13 | +map[word].push(index); |
| 14 | +}else{ |
| 15 | +map[word]=[index]; |
| 16 | +} |
| 17 | +}); |
| 18 | +} |
| 19 | + |
| 20 | +ShortestWordDist.prototype.shortest=function(word1,word2){ |
| 21 | +varlist1=this.hashMap[word1]; |
| 22 | +varlist2=this.hashMap[word2]; |
| 23 | +vardist=Math.pow(2,32)-1; |
| 24 | + |
| 25 | +for(vari=0,j=0;i<list1.length&&j<list2.length;){ |
| 26 | +varindex1=list1[i]; |
| 27 | +varindex2=list2[j]; |
| 28 | + |
| 29 | +dist=Math.min(Math.abs(index1-index2),dist); |
| 30 | +if(index1<index2){ |
| 31 | +i++; |
| 32 | +}else{ |
| 33 | +j++; |
| 34 | +} |
| 35 | +} |
| 36 | + |
| 37 | +returndist; |
| 38 | +}; |
| 39 | + |
| 40 | +// test cases |
| 41 | +varws=["practice","makes","perfect","coding","makes","google","coding","apple","alpha"]; |
| 42 | +varwords=newShortestWordDist(ws); |
| 43 | + |
| 44 | +varword1='practice'; |
| 45 | +varword2='coding'; |
| 46 | +varword3='apple'; |
| 47 | +console.log(words.shortest(word1,word2)); |
| 48 | +console.log(words.shortest(word2,word3)); |