C++/Java easy to understand solution.


  • 0
    C
    // C++   
    int shortestDistance(vector<string>& words, string word1, string word2) {
       int m = -words.size(), n = words.size(), res = words.size();
       for (unsigned int i=0; i<words.size(); i++) {
          if (words[i]==word1)
             m = i;
          if (words[i]==word2)
             n = i;
          res = min(res, abs(m-n));
       }
       return res;
    }
      
    // Java
    public int shortestDistance(String[] words, String word1, String word2) {
        int m = -words.length, n = words.length, res = words.length;
        for (int i=0; i<words.length; i++) {
            if (words[i].equals(word1))
                m = i;
            if (words[i].equals(word2))
                n = i;
            res = Math.min(res, Math.abs(m-n));
        }
        return res;
    }

Log in to reply
 

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