- 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
- 27 lines of Java from the credited upstream file 972.java.
- The implementation visibly relies on sequence storage.
- No explicit 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 isRationalEqual(String s, String t) {3 return Math.abs(valueOf(s) - valueOf(t)) < 1e-9;4 }5 6 private static double[] ratios = new double[] {1.0, 1.0 / 9, 1.0 / 99, 1.0 / 999, 1.0 / 9999};7 8 private double valueOf(final String s) {9 if (!s.contains("("))10 return Double.valueOf(s);11 12 13 final int leftParenIndex = s.indexOf('(');14 final int rightParenIndex = s.indexOf(')');15 final int dotIndex = s.indexOf('.');16 17 18 final double nonRepeating = Double.valueOf(s.substring(0, leftParenIndex));19 final int nonRepeatingLength = leftParenIndex - dotIndex - 1;20 21 22 final int repeating = Integer.parseInt(s.substring(leftParenIndex + 1, rightParenIndex));23 final int repeatingLength = rightParenIndex - leftParenIndex - 1;24 return nonRepeating + repeating * Math.pow(0.1, nonRepeatingLength) * ratios[repeatingLength];25 }26}27