删除字符串中的“b”和“ac”,需要满足如下的条件:
1. 字符串只能遍历一次
2. 不能够实用额外的空间
例如:
1. acbac ==> ""
2. aaac ==> aa
3. ababac ==> aa
4. bbbbd ==> d
5. aaccac ==> ""
1 public class Solution {
2 public String deleteChars(String s) {
3 StringBuffer sb = new StringBuffer(s);
4 int fast = 0, slow = -1;
5 int length = s.length();
6 while (fast < length) {
7 if (sb.charAt(fast) == 'b') {
8 fast++;
9 } else if (fast < length - 1 && sb.charAt(fast) == 'a' && sb.charAt(fast + 1) == 'c') {
10 fast += 2;
11 } else {
12 sb.setCharAt(++slow, sb.charAt(fast++));
13 if (slow > 0 && sb.charAt(slow - 1) == 'a' && sb.charAt(slow) == 'c') {
14 slow -= 2;
15 }
16 }
17 }
18 return sb.substring(0, slow + 1);
19 }
20 }