Prompt: Given a sentence and a set of known abbreviations, figure out an efficient way to shorten the sentence.
Abbreviations:
be right back -> BRB
be right there -> BRT
be back later -> BBL
be back soon -> B back soon
faster than light -> FTL
be -> B
later => L8R
Conversions:
I will be right there -> I will BRT
I will be there -> I will B there
I will go right there -> I will go right there
I will be there later -> I will B there L8R
I am faster than you -> I am faster than you
Never faster than light -> Never FTL
Faster than light today -> FTL today
Here's my code to this problem. However, I am only able to get one abbreviation in my final answer.
import java.util.*;
class Solution{
public static void main(String[] args) {
Map<String, String> dict = new HashMap<>();
dict.put("be right back", "BRB");
dict.put("be right there", "BRT");
dict.put("be right later", "BRL");
dict.put("be", "B");
dict.put("later", "L8R");
String s = "I will be right there later";
System.out.println(convert(s, dict));
}
public static String convert(String s, Map<String, String> dict) {
String[] words = s.split(" ");
List<String> converted = new ArrayList<>();
List<String> toCheck = new ArrayList<>();
for (int i = 0; i < words.length; i++){
for (int j = i; j < words.length; j++){
String[] substring = Arrays.copyOfRange(words, i, j+1);
String combined = "";
for (String str : substring){
combined += str + " ";
}
combined = combined.strip();
toCheck.add(combined);
}
}
String ans = "";
String target = "";
for (String str : toCheck){
if (dict.containsKey(str)){
int index = s.indexOf(str);
ans = s.substring(0, index) + dict.get(str) + s.substring(index + str.length());
}
}
return ans;
}
}
I think there is a recursive way to perform the conversion, but I am not quite sure how. Can anyone help me with that or direct me to a problem similar to this one? Thanks in advance!