I am trying to solve a problem of finding missing words in a string.
For example:
Input
String 1 = "I love programming, pizza, coke and chips";
String 2 = "I programming, chips";
Required Output
Missing words = "love pizza coke";
Note: the order of output has to be same (this is where I am messing up)
what I have so far, but I am getting wrong results.
public static List<String> findWord(String s, String t) {
HashSet<String> missingWords = new HashSet<>();
String[] words = s.split(" ");
for(int i=0; i < words.length; i++) {
if (!t.contains(words[i])) {
missingWords.add(words[i]);
}
}
List<String> ans = new ArrayList<String>();
for (String str: missingWords) {
ans.add(str);
}
return ans;
}
I would approach this by splitting both input strings, stripping off punctuation, and then walking down each array of words, in the original order. When encountering a match, both lists advance. When there is no match, the original list advances, but the second list does not, and we also record the original word as not having found a match.
The key point here is that we use an ArrayList
, which maintains insertion order, while traversing.
String input = "I love programming, pizza, coke and chips";
String other = "I programming, chips";
String[] parts = input.replaceAll("[,.;-]", "").split("\\s");
String[] otherparts = other.replaceAll("[,.;-]", "").split("\\s");
List<String> missing = new ArrayList<>();
int pnt = 0;
for (int i=0; i < parts.length; ++i) {
if (parts[i].equals(otherparts[pnt])) {
++pnt;
}
else {
missing.add(parts[i]);
}
}
System.out.println(Arrays.toString(parts));
System.out.println(Arrays.toString(missing.toArray()));
[I, love, programming, pizza, coke, and, chips]
[love, pizza, coke, and]
Demo
Demo added for informational purposes only. Do not rely on it for production use.