- 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
- 48 lines of Java from the credited upstream file 151.java.
- The implementation keeps its working state in language-native values and containers.
- 8 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 reverseWords(String s) {3 StringBuilder sb = new StringBuilder(s).reverse(); 4 reverseWords(sb, sb.length()); 5 return cleanSpaces(sb, sb.length()); 6 }7 8 private void reverseWords(StringBuilder sb, int n) {9 int i = 0;10 int j = 0;11 12 while (i < n) {13 while (i < j || i < n && sb.charAt(i) == ' ') 14 ++i;15 while (j < i || j < n && sb.charAt(j) != ' ') 16 ++j;17 reverse(sb, i, j - 1); 18 }19 }20 21 22 private String cleanSpaces(StringBuilder sb, int n) {23 int i = 0;24 int j = 0;25 26 while (j < n) {27 while (j < n && sb.charAt(j) == ' ') 28 ++j;29 while (j < n && sb.charAt(j) != ' ') 30 sb.setCharAt(i++, sb.charAt(j++));31 while (j < n && sb.charAt(j) == ' ') 32 ++j;33 if (j < n) 34 sb.setCharAt(i++, ' ');35 }36 37 return sb.substring(0, i).toString();38 }39 40 private void reverse(StringBuilder sb, int l, int r) {41 while (l < r) {42 final char temp = sb.charAt(l);43 sb.setCharAt(l++, sb.charAt(r));44 sb.setCharAt(r--, temp);45 }46 }47}48