鱼C论坛

 找回密码
 立即注册
查看: 1411|回复: 0

[学习笔记] leetcode 1209. Remove All Adjacent Duplicates in String II

[复制链接]
发表于 2019-9-30 07:00:58 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. 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.

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

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

  4. It is guaranteed that the answer is unique.



  5. Example 1:

  6. Input: s = "abcd", k = 2
  7. Output: "abcd"
  8. Explanation: There's nothing to delete.
  9. Example 2:

  10. Input: s = "deeedbbcccbdaa", k = 3
  11. Output: "aa"
  12. Explanation:
  13. First delete "eee" and "ccc", get "ddbbbdaa"
  14. Then delete "bbb", get "dddaa"
  15. Finally delete "ddd", get "aa"
  16. Example 3:

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


  19. Constraints:

  20. 1 <= s.length <= 10^5
  21. 2 <= k <= 10^4
  22. s only contains lower case English letters.
复制代码

  1. class Solution {
  2.     public String removeDuplicates(String s, int k) {
  3.         Stack <Character> stack_c = new Stack<>();
  4.         Stack <Integer> stack_n = new Stack<>();
  5.         
  6.         for(int i = 0; i < s.length(); i++){
  7.             
  8.             if(!stack_c.isEmpty() && stack_c.peek() == s.charAt(i)){
  9.                
  10.                 stack_n.push(stack_n.peek()+1);
  11.             }else{
  12.                
  13.                 stack_n.push(1);
  14.             }
  15.             
  16.             stack_c.push(s.charAt(i));
  17.             
  18.             if(stack_n.peek() == k){
  19.                
  20.                 for(int j = 0; j< k ; j++){
  21.                     
  22.                     stack_n.pop();
  23.                     stack_c.pop();
  24.                 }
  25.             }
  26.         }
  27.         
  28.         StringBuilder ret = new StringBuilder();
  29.         
  30.         while(!stack_c.isEmpty()){
  31.             
  32.             ret.append(stack_c.pop());
  33.         }
  34.         
  35.         return ret.reverse().toString();
  36.     }
  37. }
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-1 19:28

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表