[leetcode] 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".

 
    

分析:题目要求很简单,两个字符串S和T,每个字符串中都有'#'字符,遇到'#'字符就要往后删掉一个,最后判断操作后的结果是否相等。题目很好理解,关键要能想到'#'出现的位置,如果#前面没有字符了,那就应该忽略。找准这个,题目的解法就比较容易了。这里我用了一个helper函数来完成对字符串的back操作。用一个stringbuffer来记录结果。代码如下:

 1     public boolean backspaceCompare(String S, String T) {
 2         return helper(S).equals(helper(T));
 3     }
 4     private String helper(String s){
 5         StringBuilder res = new StringBuilder("");
 6         int cur = 0;
 7         while ( cur < s.length() ){
 8             char c = s.charAt(cur);
 9             if ( c == '#' && res.length() != 0) res.deleteCharAt(res.length()-1);
10             if ( c != '#') res.append(c);
11             cur++;
12         }
13 //        System.out.println(res);
14         return res.toString();
15     }

提交结果还是比较好的,运行时间5ms,击败了99.84的提交次数。

猜你喜欢

转载自www.cnblogs.com/boris1221/p/9280349.html