Concise and clean C++ code.


  • 0
    M
    class Solution {
    public:
        int shortestWordDistance(vector<string>& words, string word1, string word2) 
    {
            int dist = INT_MAX;
        	int startIndex = -1;
        	for (int i = 0; i < words.size(); ++i)
        	{
        		if (words[i] == word1 || words[i] == word2)
        		{
        			if (startIndex != -1 && (word1 != word2 && words[startIndex] != words[i] || word1 == word2))
        			{
        				dist = min(dist, i - startIndex);
        			}
        			
        			startIndex = i;
        		}
        	}
        
        	return dist;
        }
    };
    

Log in to reply
 

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