Created
June 6, 2024 09:53
-
-
Save samarthsewlani/937c5b36c91b7694e9a907c66d45b90f to your computer and use it in GitHub Desktop.
Remove All Adjacent In String 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/description/ | |
class Solution { | |
public String removeDuplicates(String s, int k) { | |
Deque<Character> stack = new ArrayDeque<>(); | |
Deque<Integer> nums = new ArrayDeque<>(); | |
stack.push('#'); nums.push(1); | |
int n = s.length(); | |
for(int i=0;i<n;i++){ | |
if(s.charAt(i) == stack.peek()){ | |
nums.push(nums.peek()+1); | |
} | |
else{ | |
nums.push(1); | |
} | |
stack.push(s.charAt(i)); | |
if(nums.peek()==k) popKtimes(nums, stack, k); | |
} | |
StringBuilder sb = new StringBuilder(); | |
while(stack.size()>1) sb.append(stack.pop()); | |
sb.reverse(); | |
return sb.toString(); | |
} | |
public void popKtimes(Deque<Integer> nums, Deque<Character> stack, int k){ | |
int c = 0; | |
while(c<k){ | |
nums.pop(); stack.pop(); c++; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment