- 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
- 31 lines of Java from the credited upstream file 2018.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 boolean placeWordInCrossword(char[][] board, String word) {3 for (char[][] state : new char[][][] {board, getRotated(board)})4 for (char[] chars : state)5 for (final String token : String.valueOf(chars).split("#"))6 for (final String letters :7 new String[] {word, new StringBuilder(word).reverse().toString()})8 if (letters.length() == token.length())9 if (canFit(letters, token))10 return true;11 return false;12 }13 14 private char[][] getRotated(char[][] board) {15 final int m = board.length;16 final int n = board[0].length;17 char[][] rotated = new char[n][m];18 for (int i = 0; i < m; ++i)19 for (int j = 0; j < n; ++j)20 rotated[j][i] = board[i][j];21 return rotated;22 }23 24 private boolean canFit(final String letters, final String token) {25 for (int i = 0; i < letters.length(); ++i)26 if (token.charAt(i) != ' ' && token.charAt(i) != letters.charAt(i))27 return false;28 return true;29 }30}31