Java simple solution


  • 1
    J
    public class Solution {
    public int shortestWordDistance(String[] words, String word1, String word2) {
    	int min = words.length;
    	int pos1 = -1, pos2 = -1;
    
    	if (word1.equals(word2)) {
    		for (int i = 0; i < words.length; i++) {
    			if (words[i].equals(word1)) {
    				if (pos1 != -1) {
    					min = Math.min(min,  i - pos1);
    				}
    				pos1 = i;
    			}
    		}
    
    	} else {
    		for (int i = 0; i < words.length; i++) {
    			if (words[i].equals(word1))
    				pos1 = i;
    			else if (words[i].equals(word2))
    				pos2 = i;
    			else
    				continue;
    
    			if (pos1 != -1 && pos2 != -1) {
    				min = Math.min(min, Math.abs(pos2 - pos1));
    			}
    		}
    	}
    	return min;
    
    }
    

    }


Log in to reply
 

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