Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.
Example 1:
Input: S = "ab#c", T = "ad#c" Output: true Explanation: Both S and T become "ac".
Example 2:
Input: S = "a##c", T = "#a#c" Output: true Explanation: Both S and T become "c".
1 class Solution { 2 public boolean backspaceCompare(String S, String T) { 3 int i = S.length() - 1, j = T.length() - 1; 4 5 while (i >= 0 || j >= 0) { 6 int c1 = 0; 7 while (i >= 0 && (c1 > 0 || S.charAt(i) == ‘#‘)) { 8 if (S.charAt(i) == ‘#‘) { 9 c1++; 10 } else { 11 c1--; 12 } 13 i--; 14 } 15 16 int c2 = 0; 17 while (j >= 0 && (c2 > 0 || T.charAt(j) == ‘#‘)) { 18 if (T.charAt(j) == ‘#‘) { 19 c2++; 20 } else { 21 c2--; 22 } 23 j--; 24 } 25 26 if (i >= 0 && j >= 0) { 27 if (S.charAt(i) != T.charAt(j)) { 28 return false; 29 } else { 30 i--; 31 j--; 32 } 33 } else { 34 if (i >= 0 || j >= 0) { 35 return false; 36 } 37 } 38 } 39 40 return i < 0 && j < 0; 41 } 42 }
原文:https://www.cnblogs.com/beiyeqingteng/p/14141970.html