- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 85 lines of Java from the credited upstream file 411.java.
- The implementation visibly relies on sequence storage.
- 7 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public String minAbbreviation(String target, String[] dictionary) {3 final int m = target.length();4 List<Integer> masks = new ArrayList<>();5 6 for (final String word : dictionary) {7 if (word.length() != m)8 continue;9 masks.add(getMask(target, word));10 }11 12 if (masks.isEmpty())13 return String.valueOf(m);14 15 List<String> abbrs = new ArrayList<>();16 17 final int maxCand = (int) Math.pow(2, m);18 19 for (int i = 0; i < maxCand; ++i) {20 final int cand = i;21 22 if (masks.stream().allMatch(mask -> (cand & mask) > 0))23 abbrs.add(getAbbr(target, cand));24 }25 26 String ans = target;27 28 for (final String abbr : abbrs)29 if (getAbbrLen(abbr) < getAbbrLen(ans))30 ans = abbr;31 32 return ans;33 }34 35 private int getMask(final String target, final String word) {36 final int m = target.length();37 38 39 40 41 42 int mask = 0;43 for (int i = 0; i < m; ++i)44 if (word.charAt(i) != target.charAt(i))45 mask |= 1 << m - 1 - i;46 return mask;47 }48 49 String getAbbr(final String target, int cand) {50 final int m = target.length();51 StringBuilder sb = new StringBuilder();52 int replacedCount = 0;53 for (int i = 0; i < m; ++i)54 if ((cand >> m - 1 - i & 1) == 1) {55 56 if (replacedCount > 0)57 sb.append(replacedCount);58 sb.append(target.charAt(i));59 replacedCount = 0;60 } else {61 62 ++replacedCount;63 }64 if (replacedCount > 0)65 sb.append(replacedCount);66 return sb.toString();67 }68 69 int getAbbrLen(final String abbr) {70 int abbrLen = 0;71 int i = 0;72 int j = 0;73 while (i < abbr.length()) {74 if (Character.isAlphabetic(abbr.charAt(j)))75 ++j;76 else77 while (j < abbr.length() && Character.isDigit(abbr.charAt(j)))78 ++j;79 ++abbrLen;80 i = j;81 }82 return abbrLen;83 }84}85