package pack1;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
public class AGShortestSegment {
public static void main(String[] args) {
String paragraph = "This is a test. This is a programming test.
This is a programming test";
String toFind = "This a programming test";
List listOfParagraphWords = getListOfWords(paragraph);
List matchList = getListOfWords(toFind);
List shortestSegment = getShortestSegment(listOfParagraphWords,
matchList);
System.out.println(shortestSegment);
}
private static List getShortestSegment(List listOfWords, List
matchList) {
List segment = new ArrayList();
List shortestRequiredSegment = listOfWords;
for(int i = 0 ; i < listOfWords.size(); i++) {
if(shortestRequiredSegment.size() == matchList.size()) {
break;
}
for (int j = i + matchList.size()-1; j < listOfWords.size() ;
j++) {
segment = listOfWords.subList(i, j+1);
if (segment.containsAll(matchList) &&
segment.toString().length() <
shortestRequiredSegment.toString().length()) {
shortestRequiredSegment = segment;
break;
}
}
}
return shortestRequiredSegment;
}
private static List getListOfWords(String paragraph) {
List listOfWords = new ArrayList();
String word = "";
char[] parray = paragraph.toCharArray();
for(char pchar : parray) {
boolean isAnAlphabet = Pattern.matches("[a-zA-z]",
((Character)pchar).toString());
if(isAnAlphabet) {
word+=pchar;
} else {
if (!word.trim().equals("")) {
listOfWords.add(word);
}
word = "";
}
}
listOfWords.add(word);
return listOfWords;
}
}
--
You received this message because you are subscribed to the Google Groups
"Algorithm Geeks" group.
To unsubscribe from this group, send email to
[email protected].
For more options, visit https://groups.google.com/groups/opt_out.