Clear O(n) C++ Solution


  • 0
    L
    class Solution {
    public:
        int shortestWordDistance(vector<string>& words, string word1, string word2) {
            int distance = words.size();
            int pos1 = -distance;
            int pos2 = pos1 + 1;
            
            for (int i = 0; i < words.size(); i++) {
                
                if (words[i] != word1 && words[i] != word2) {
                    continue;
                }
                else if (words[i] == word1 && words[i] == word2) {
                    if (pos1 < pos2) {
                        pos1 = i;
                    }
                    else {
                        pos2 = i;
                    }
                }
                else if (words[i] == word1) {
                    pos1 = i;
                }
                else {
                    pos2 = i;
                }
                distance = min(distance, abs(pos1 - pos2));
            }
            return distance;
        }
    };

Log in to reply
 

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