classSolution{ publicbooleanbackspaceCompare(String s, String t){ String a = process(s.toCharArray()); String b = process(t.toCharArray()); return a.equals(b); } private String process(char[] array){ int i = 0; for (int j = 0; j < array.length; j++) { if (array[j] == '#') { if (i > 0) { i--; } } else { array[i++] = array[j]; } } returnnew String(array, 0, i); } }
Solution 2
scan the 2 strings from the back at the same time. Because after we processed the index i from the back, the value of index i will not be changed anymore. Also, we don’t need extra space to store the intermediate result during the process.