why golang solution can't pass


  • 0
    T

    this is my solution:

    
    type WordDistance struct {
    	hash map[string][]int
    }
    
    func Constructor(words []string) WordDistance {
    	wd := WordDistance{}
    	wd.hash = make(map[string][]int)
    	for i, w := range words {
    		list, ok := wd.hash[w]
    		if ok {
    			wd.hash[w] = append(list, i)
    		} else {
    			wd.hash[w] = []int{i}
    		}
    	}
    	return wd
    }
    
    func (this *WordDistance) Shortest(word1 string, word2 string) int {
    	d1, d2 := this.hash[word1], this.hash[word2]
    	result := len(this.hash)
    	i, j := 0, 0
    	for i < len(d1) && j < len(d2) {
    		di, dj := d1[i], d2[j]
    		if di < dj {
    			result = min(result, dj-di)
    			i++
    		} else {
    			result = min(result, di-dj)
    			j++
    		}
    	}
    	return result
    }
    
    func min(a int, b int) int {
    	if a < b {
    		return a
    	}
    	return b
    }
    
    

    I am confusing why I can pass Python and Java version, but Golang will fail the last case.

    Thanks


Log in to reply
 

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