top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

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

+2 votes
492 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 by Mohammed Hussain

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer
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;
    }
answer Nov 5, 2015 by Manikandan J
Similar Questions
+2 votes

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

C/Java code would be helpful?

+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.

+4 votes

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?

+8 votes

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

0 votes

Find the first non repeating character in a string.

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

...