Tuesday, February 22, 2011

Find common sequence that is out of order between two given strings in Java

/*
Given two strings, find the longest common sequence that is out of order. Initially it was royally confusing to me what the question meant, but I was able to come up with a solution. Please see the following program implemented in Java. The sample inputs and outputs have been provided at the end.
*/
Hashing is Most Efficient Solution

import java.util.LinkedHashMap;
import java.util.Map;

public class Sequence {
public static void main(String[] args) {
Sequence seq = new Sequence();
String str1 = "a111b3455yy";
String str2 = "byy115789";
System.out.println("Input1: "+str1);
System.out.println("Input2: "+str2);
String solution = seq.findCommonSequnce(str1, str2);
System.out.println("Output: "+solution);
}

public String findCommonSequnce(String str1, String str2){
if(str1==null || str2==null){
return "";
}
if(str1.length() == 0 || str2.length() == 0){
return "";
}
//parse first String store the frequency of characters
//in a hashmap
Map firstStringMap = frequencyMap(str1);

StringBuilder output = new StringBuilder();

for(int i=0;i int count = 0;
if(firstStringMap.containsKey(str2.charAt(i)) && (count=firstStringMap.get(str2.charAt(i)))>0){
output.append(str2.charAt(i));
firstStringMap.put(str2.charAt(i), --count);
}
}

return output.toString();
}

/**
* Returns a map with character as the key and its occurence as the value
* @param str
* @return
*/
private Map frequencyMap(String str) {
Map freqMap = new LinkedHashMap();
for(int i=0;i Integer count = freqMap.get(str.charAt(i));
if(count==null){//means the frequency is yet to stored
freqMap.put(str.charAt(i), 1);
}else{
freqMap.put(str.charAt(i), ++count);
}
}
return freqMap;
}
}

//SAMPLE OUTPUTS
//Input1: a111b3455yy
//Input2: byy115789
//Output: byy115

2 comments :

Nope said...

Can you give some more test cases .
It is not very clear as to what we're supposed to do in this question.

Unknown said...

@richi we are finding matching non- contiguous substring in two given string hope it will help ..do notify me if it will fail for any test case..:)