C++ stack


  • 0
    B
    class Solution {
    public:
        int shortestWordDistance(vector<string>& words, string word1, string word2) {
            stack<int>stk1,stk2;
            int ans = INT_MAX;
            for(int i = 0; i < words.size(); i++)
            {
                if(words[i] == word1)
                {
                    if(word1 == word2 && !stk1.empty())
                    {
                        ans = min(ans, i - stk1.top());
                    }
                    stk1.push(i);
                }
                else if(words[i] == word2)
                {
                    stk2.push(i);
                }
                if(word1 != word2 && !stk1.empty() && !stk2.empty()) ans = min(ans, abs(stk1.top()-stk2.top()));
            }
            return ans;
        }
    };

Log in to reply
 

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