844. Backspace String Compare
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 String s1 = processRawString(S); 4 String t1 = processRawString(T); 5 return s1.equals(t1); 6 } 7 8 private String processRawString(String rawString) { 9 if (rawString == null || rawString.isEmpty()) { 10 return ""; 11 } 12 Stack<Character> processedString = new Stack<>(); 13 for (int i = 0; i < rawString.length(); i++) { 14 char ch = rawString.charAt(i); 15 if (ch == '#') { 16 if (!processedString.isEmpty()) { 17 processedString.pop(); 18 } 19 } else { 20 processedString.push(ch); 21 } 22 } 23 StringBuilder result = new StringBuilder(); 24 while (!processedString.isEmpty()) { 25 result.insert(0, processedString.pop()); 26 } 27 return result.toString(); 28 } 29 }
如果要求不能使用extra space, 那么我们可以从后往前process.
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 }