C++ solution, better initialzation


  • 1
    C
    class Solution {
    public:
        int shortestDistance(vector<string>& words, string word1, string word2) {
            int index1 = -words.size(); // initial variable in this way , so if index isn't initialized yet, the distance will be larger than array size and won't be stored in short_dist
            int index2 = -words.size();
            int short_dist = words.size();
            for( int i = 0; i< words.size();++i)
            {
                if ( words[i] == word1 )
                {
                    short_dist = min(short_dist, i-index2);
                    index1 = i;
                }
                else if ( words[i] == word2)
                {
                    short_dist = min(short_dist, i-index1);
                    index2 = i;
                }
            }
            return short_dist;
        }
    };
    

Log in to reply
 

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