98.3% 13ms C++ solution


  • 0
    R
    class Solution {
    public:
        int shortestDistance(vector<string>& words, string word1, string word2) {
            int start = -1, end = -1, distance = INT_MAX;
            for(int i = 0; i < words.size(); i++){
                if(words[i] == word1)
                    start = i;
                if(words[i] == word2)
                    end = i;
                if(start >= 0 && end >= 0)
                    distance = min(distance, abs(end-start));
            }
            return distance;
        }
    };
    

Log in to reply
 

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