Created
July 15, 2018 00:28
-
-
Save ramannanda9/9e75dd5b0f0b17b6e5729d9930320ebe to your computer and use it in GitHub Desktop.
Least Distance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*package whatever //do not write package name here */ | |
import java.util.*; | |
import java.lang.*; | |
import java.io.*; | |
import java.util.Scanner; | |
class GFG { | |
public int getMinDistance(String[] words,String word1,String word2){ | |
int minDistance=Integer.MAX_VALUE; | |
int w1=0;int w2=0; | |
boolean word1Matched=false; | |
boolean word2Matched=false; | |
for(int i=0;i<words.length;i++){ | |
if(minDistance==0) break; | |
String word=words[i]; | |
if(word1.matches(word)){ | |
word1Matched=true; | |
w1=i; | |
} | |
if(word2.matches(word)){ | |
word2Matched=true; | |
w2=i; | |
} | |
if(word1Matched&&word2Matched){ | |
if(Math.abs(w1-w2)<minDistance){ | |
minDistance=Math.abs(w1-w2); | |
} | |
if(w2>w1){ | |
w1=0; | |
word1Matched=false; | |
} | |
else{ | |
w2=0; | |
word2Matched=false; | |
} | |
} | |
} | |
return minDistance; | |
} | |
public static void main (String[] args) { | |
Scanner scanner=new Scanner(System.in); | |
GFG gfg=new GFG(); | |
int testCases=Integer.parseInt(scanner.nextLine().trim()); | |
for(int i=0;i<testCases;i++){ | |
scanner.nextLine(); | |
String[] words=scanner.nextLine().split("\\s+"); | |
String[] wordsToSearch=scanner.nextLine().split("\\s+"); | |
System.out.println(gfg.getMinDistance(words, | |
wordsToSearch[0],wordsToSearch[1])); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment