题目

Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.

We repeatedly make k duplicate removals on s until we no longer can.

Return the final string after all such duplicate removals have been made.

It is guaranteed that the answer is unique.

Example 1:

  1. Input: s = "abcd", k = 2
  2. Output: "abcd"
  3. Explanation: There's nothing to delete.

Example 2:

  1. Input: s = "deeedbbcccbdaa", k = 3
  2. Output: "aa"
  3. Explanation:
  4. First delete "eee" and "ccc", get "ddbbbdaa"
  5. Then delete "bbb", get "dddaa"
  6. Finally delete "ddd", get "aa"

Example 3:

  1. Input: s = "pbbcggttciiippooaais", k = 2
  2. Output: "ps"

Constraints:

  • 1 <= s.length <= 10^5
  • 2 <= k <= 10^4
  • s only contains lower case English letters.

题意

给定一个字符串s和整数k,遍历s,如果遇到k个连续字符都相同,则删去这k个字符,并得到新字符串t,对t进行同样的操作,直到最后无字符可删。返回最终得到的字符串。

思路

维护两个栈,分别保存字符和其对应的连续的次数。遍历字符串,如果当前字符与前一个不同,将前一个字符和对应次数压栈;如果当前字符与前一个相同,连续次数累加。然后判断连续次数是否已达到k,如果是则出栈前一个字符和对应次数(相当于将当前字符抛弃)。注意遍历到最后一个字符串时要进行特殊处理。


代码实现

Java

  1. class Solution {
  2. public String removeDuplicates(String s, int k) {
  3. Deque<Character> chars = new ArrayDeque<>();
  4. Deque<Integer> cnts = new ArrayDeque<>();
  5. int cnt = 0;
  6. Character pre = null;
  7. for (int i = 0; i < s.length(); i++) {
  8. char cur = s.charAt(i);
  9. if (pre == null) {
  10. pre = cur;
  11. cnt = 1;
  12. } else if (cur == pre) {
  13. cnt++;
  14. }else {
  15. chars.push(pre);
  16. cnts.push(cnt);
  17. pre = cur;
  18. cnt = 1;
  19. }
  20. if (i == s.length() - 1 && cnt < k) {
  21. chars.push(pre);
  22. cnts.push(cnt);
  23. } else if (i < s.length() - 1 && cnt == k) {
  24. pre = chars.isEmpty() ? null : chars.pop();
  25. cnt = cnts.isEmpty() ? 0 : cnts.pop();
  26. }
  27. }
  28. StringBuilder sb = new StringBuilder();
  29. while (!chars.isEmpty()) {
  30. sb.append((chars.removeLast() + "").repeat(cnts.removeLast()));
  31. }
  32. return sb.toString();
  33. }
  34. }