Skip to content

Commit 165ef04

Browse files
authored
Merge pull request #1924 from AkifhanIlgaz/1209
Create: 1209-remove-all-adjacent-duplicates-in-string-II.rs / .ts
2 parents 1f63332 + ebeff45 commit 165ef04

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
impl Solution {
2+
pub fn remove_duplicates(s: String, k: i32) -> String {
3+
let mut stack: Vec<(char, usize)> = vec![];
4+
for ch in s.chars() {
5+
if !stack.is_empty() && stack.last().unwrap().0 == ch {
6+
let mut last = stack.pop().unwrap();
7+
last.1 += 1;
8+
stack.push(last);
9+
} else {
10+
stack.push((ch, 1));
11+
}
12+
if stack.last().unwrap().1 == k as usize {
13+
stack.pop();
14+
}
15+
}
16+
17+
stack.iter().fold(String::new(), |acc, &(ch, count)| {
18+
acc + &ch.to_string().repeat(count)
19+
})
20+
}
21+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
function removeDuplicates(s: string, k: number): string {
2+
const stack: { char: string; count: number }[] = []; // [char, count];
3+
4+
for (const c of s) {
5+
if (stack.length !== 0 && stack[stack.length - 1].char === c) {
6+
stack[stack.length - 1].count++;
7+
} else {
8+
stack.push({ char: c, count: 1 });
9+
}
10+
11+
if (stack[stack.length - 1].count === k) {
12+
stack.pop();
13+
}
14+
}
15+
16+
return stack.reduce(
17+
(acc, { char, count }) => (acc += char.repeat(count)),
18+
''
19+
);
20+
}

0 commit comments

Comments
 (0)