Is the input array or list?


  • 0
    K
    public static int shortestDistance(String[] words, String word1, String word2) {
        List<Integer> word1Positions = new ArrayList<>();
        List<Integer> word2Positions = new ArrayList<>();
        for(int i=0; i< words.length; i++){
            if(words[i]==word1){
                word1Positions.add(i);
            } else if(words[i] == word2){
                word2Positions.add(i);
            }
        }
        int shortestDistance=99999;
        for(Integer word1Position : word1Positions){
            for(Integer word2Position : word2Positions){
                int temp;
                if(word1Position>word2Position){
                    temp = word1Position-word2Position;
                } else {
                    temp = word2Position-word1Position;
                }
                if(temp<shortestDistance){
                    shortestDistance=temp;
                }
            }
        }
        return shortestDistance;
    }
    

    I am getting correct results when I call this method from main on my IDE (IntelliJ). My main method is as follows:

    public static void main(String args[]){
        String[] words = {"a","b"};
        String word1 = "a";
        String word2 = "b";
        System.out.println(shortestDistance(words,word1,word2));
    
    }
    

    Am I assuming something incorrect?


Log in to reply
 

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