fork download
  1. import java.util.*;
  2. class Solution{
  3. public static void main(String[] args) {
  4. Map<String, String> dict = new HashMap<>();
  5. dict.put("be right back", "BRB");
  6. dict.put("be right there", "BRT");
  7. dict.put("be right later", "BRL");
  8. dict.put("be", "B");
  9. dict.put("be back soon","B back soon");
  10. dict.put("faster than light","FTL");
  11. dict.put("later", "L8R");
  12.  
  13. String[] tests = {
  14. "I will be right there later",
  15. "I will be right there",
  16. "I will be there",
  17. "I will go right there",
  18. "I will be there later",
  19. "I am faster than you",
  20. "Never faster than light",
  21. "Faster than light today"
  22. };
  23.  
  24. for(String test_case : tests){
  25. System.out.println(test_case + " => " + convert(test_case, dict));
  26. }
  27. }
  28.  
  29. public static String convert(String s, Map<String, String> dict) {
  30.  
  31. List<String> dict_words = new ArrayList<>(dict.keySet());
  32. Map<Integer,String[]> replacement_index = new HashMap<>();
  33.  
  34. Collections.sort(dict_words,new Comparator<String>(){
  35. public int compare(String s1,String s2){
  36. if(s1.length() == s2.length()) return 0; // order doesn't seem to matter for same length strings
  37. return s2.length() - s1.length(); // return bigger length string first
  38. }
  39. });
  40.  
  41. String temp = s.toLowerCase(); // to perform case insensitive match
  42. for(String dict_str : dict_words){
  43. String dict_str_lower = dict_str.toLowerCase(); // to perform case insensitive match
  44. int index = 0;
  45. do{
  46. index = temp.indexOf(dict_str_lower,index);
  47. if(index != -1){
  48. replacement_index.putIfAbsent(index,new String[]{dict.get(dict_str),dict_str});
  49. index++;// to get the next match index of the same word in the string.
  50. }
  51. }while(index != -1 && index < temp.length());
  52. }
  53.  
  54. StringBuilder res = new StringBuilder("");
  55.  
  56. for(int i = 0;i < s.length(); ++i){
  57. if(replacement_index.containsKey(i)){
  58. res.append(replacement_index.get(i)[0]);
  59. i += replacement_index.get(i)[1].length() - 1;
  60. }else{
  61. res.append(s.charAt(i));
  62. }
  63. }
  64.  
  65. return res.toString();
  66. }
  67.  
  68. }
Success #stdin #stdout 0.14s 36356KB
stdin
Standard input is empty
stdout
I will be right there later => I will BRT L8R
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