# Find minimum distance between two words (order preserved) in a big string?

235 views

For
e.g 1. "hello how are you" - distance between "hello" and "you" is 3.
e.g 2. "hello how are hello you" - distance is 1
e.g 3. "you are hello" - distance is -1. Order of "hello" and "you" should be preserved.
e.g 4. "hello how are hello" - distance is -1 since "you" did not occur even once.

posted Oct 30, 2015

+1 vote

``````public static int distance(String str,String a,String b){
int aIndex=-1;
int bIndex=-1;
int minDistance=Integer.MAX_VALUE;
String[] aS=str.toLowerCase().split("[ \t]+");
int i=0;
for(String t:aS){
if(t.equals(a)){
aIndex=i;
}
if(t.equals(b)){
bIndex=i;
}
if(aIndex!=-1 && bIndex!=-1){
minDistance= minDistance > Math.abs(bIndex-aIndex) ? bIndex-aIndex : minDistance;
}
i++;
}
if(aIndex ==-1 || bIndex==-1)
return -1;
else
return minDistance;
}
``````
Similar Questions

Given a string and two words which are present in the string, find the minimum distance between the words

Example:
"the brown quick frog quick the", "the" "quick"
Min Distance: 1

"the quick the brown quick brown the frog", "the" "brown"
Min Distance: 2

+1 vote

Given a string and dictionary of words, form a word by removing minimum number of characters.
Characters can be removed in-order only.

Given a dictionary of strings and another string find out if the string is an exact match to some words in the dictionary or varies at most in only one place of some word of the dictionary?

Convert the given string into palindrome with minimum number of appends(at end of the given string). O(n) algorithm will be appreciated ??

Input :=> Malayal
Output :=> Malayalam

Find the first non repeating character in a string.

For example
Input string: "abcdeabc"
Output: "e"