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 = "ab##", T = "c#d#" Output: true Explanation: Both S and T become "". Example 3: Input: S = "a##c", T = "#a#c" Output: true Explanation: Both S and T become "c". Example 4: Input: S = "a#c", T = "b" Output: false Explanation: S becomes "c" while T becomes "b". class Solution { public boolean backspaceCompare(String S, String T) { return simplify(S).equals(simplify(T)); } private String simplify(String s){ StringBuilder sb = new StringBuilder(); Stack<Character> stack = new Stack<>(); for(int i = 0; i < s.length(); i++){ char c = s.charAt(i); if(c == '#' && !stack.isEmpty()){ stack.pop(); } if(Character.isLetter(c)){ // don't use else here. incase when the stack is empty and cur char is "#" stack.push(c); } } while(!stack.isEmpty()) sb.append(stack.pop()); return sb.toString(); // need to convert to string . can't use .equals for stringBuilder ? } } Two StringBuilder objects are never equal. Use .toString() to get the string representation for both the objects and then use .equals() to compare the objects.
posted on 2018-09-20 18:31 猪猪🐷 阅读(129) 评论(0) 收藏 举报
浙公网安备 33010602011771号