Advertisement
Guest User

Untitled

a guest
Feb 25th, 2020
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.16 KB | None | 0 0
  1. public class Solution {
  2. /**
  3. * @param word: the given word
  4. * @return: the generalized abbreviations of a word
  5. */
  6. public List<String> generateAbbreviations(String word) {
  7.  
  8. // Write your code here
  9.  
  10.  
  11.  
  12. Set<String> set = helper(word);
  13.  
  14.  
  15. return new ArrayList<>(set);
  16. }
  17.  
  18. Map<String, Set<String>> memo = new HashMap<>();
  19.  
  20. //'ab'
  21. private Set<String> helper(String w) {
  22.  
  23. if (memo.get(w) != null) {
  24. return memo.get(w);
  25. }
  26.  
  27. Set<String> ans = new HashSet<>();
  28.  
  29. if (w.length() == 1) {
  30. ans.add(w);
  31. ans.add("1");
  32. return ans;
  33. }
  34.  
  35. // 'abcd' => 'a' 'bcd' => 'a' 'b' 'cd'
  36. // 'abcd' => 'ab' 'cd' => 'a' 'b' 'cd'
  37.  
  38. // i include in first part
  39. for (int i = 0; i < w.length() - 1; i++) {
  40.  
  41. // 'a' '1'
  42. Set<String> firstPart = helper(w.substring(0, i+1));
  43. // 'b' '1'
  44. Set<String> secondPart = helper(w.substring(i+1, w.length()));
  45.  
  46.  
  47. for (String first : firstPart) {
  48. for (String second :secondPart) {
  49.  
  50.  
  51. Integer firstBack = getBackDigit(first);
  52. Integer secondFront = getFrontDigit(second);
  53.  
  54. if (firstBack != null && secondFront != null) {
  55. // a10
  56. // 10b
  57.  
  58. ans.add(
  59. first.substring(0, first.length() - String.valueOf(firstBack).length()) + //'a'
  60. (firstBack + secondFront) + // 20
  61. second.substring(String.valueOf(secondFront).length(), second.length()) // 'b'
  62. );
  63.  
  64. } else {
  65. // 'a' 1
  66. // 'a' 'b'
  67. // 1 'b'
  68.  
  69. ans.add((first + second));
  70. }
  71. }
  72. }
  73. }
  74.  
  75. memo.put(w, ans);
  76.  
  77. return ans;
  78. }
  79.  
  80. boolean isDigit(char c) {
  81. return c >= '0' && c <= '9';
  82. }
  83.  
  84. Integer getFrontDigit(String s) {
  85.  
  86. if (!isDigit(s.charAt(0))) {
  87. return null;
  88. }
  89.  
  90. int curr = 0;
  91.  
  92. int i = 0;
  93. while (i < s.length() && isDigit(s.charAt(i))) {
  94. curr = curr * 10;
  95. curr += s.charAt(i) - '0';
  96. i++;
  97. }
  98.  
  99. return curr;
  100. }
  101.  
  102. Integer getBackDigit(String s) {
  103. if (!isDigit(s.charAt(s.length() - 1))) {
  104. return null;
  105. }
  106.  
  107. int k = 1;
  108. int curr = 0;
  109.  
  110. int i = s.length() - 1;
  111. while (i >=0 && isDigit(s.charAt(i))) {
  112. curr += (s.charAt(i) - '0') * k;
  113. i--;
  114. k = k * 10;
  115. }
  116. return curr;
  117. }
  118. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement