class Solution { public boolean backspaceCompare(String S, String T) { int len1 = S.length(); int len2 = T.length(); Deque<Character> stack1 = new LinkedList<>(); Deque<Character> stack2 = new LinkedList<>(); for (int i = 0; i < len1; i++) { Character c = S.charAt(i); if (!stack1.isEmpty() && c == '#') { stack1.pollLast(); } else if (stack1.isEmpty() && c== '#') { continue; } else { stack1.offerLast(c); } } for (int i = 0; i < len2; i++) { Character c = T.charAt(i); if (!stack2.isEmpty() && c == '#') { stack2.pollLast(); } else if (stack2.isEmpty() && c == '#') { continue; } else { stack2.offerLast(c); } } if (stack1.size() != stack2.size()) { return false; } while (!stack1.isEmpty() && !stack2.isEmpty()) { Character c1 = stack1.pollFirst(); Character c2 = stack2.pollFirst(); if (c1 != c2) { return false; } } return true; }}
class Solution { public boolean backspaceCompare(String S, String T) { int len1 = S.length() - 1; int len2 = T.length() - 1; int skip1 = 0; int skip2 = 0; while (len1 >= 0 || len2 >= 0) { while (len1 >= 0) { if (S.charAt(len1) == '#') { ++skip1; --len1; } else if (skip1 > 0) { --skip1; --len1; } else { break; } } while (len2 >= 0) { if (T.charAt(len2) == '#') { ++skip2; --len2; } else if (skip2 > 0) { --skip2; --len2; } else { break; } } if (len1 >= 0 && len2 >= 0) { if (S.charAt(len1) != T.charAt(len2)) { return false; } } else { if (len1 >= 0 || len2 >= 0) { return false; } } --len1; --len2; } return true; }}