forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create: 1209-remove-all-adjacent-duplicates-in-string-II.rs / .ts
- Loading branch information
1 parent
ee7a3bc
commit ebeff45
Showing
2 changed files
with
41 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
impl Solution { | ||
pub fn remove_duplicates(s: String, k: i32) -> String { | ||
let mut stack: Vec<(char, usize)> = vec![]; | ||
for ch in s.chars() { | ||
if !stack.is_empty() && stack.last().unwrap().0 == ch { | ||
let mut last = stack.pop().unwrap(); | ||
last.1 += 1; | ||
stack.push(last); | ||
} else { | ||
stack.push((ch, 1)); | ||
} | ||
if stack.last().unwrap().1 == k as usize { | ||
stack.pop(); | ||
} | ||
} | ||
|
||
stack.iter().fold(String::new(), |acc, &(ch, count)| { | ||
acc + &ch.to_string().repeat(count) | ||
}) | ||
} | ||
} |
20 changes: 20 additions & 0 deletions
20
typescript/1209-remove-all-adjacent-duplicates-in-string-II.ts
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
function removeDuplicates(s: string, k: number): string { | ||
const stack: { char: string; count: number }[] = []; // [char, count]; | ||
|
||
for (const c of s) { | ||
if (stack.length !== 0 && stack[stack.length - 1].char === c) { | ||
stack[stack.length - 1].count++; | ||
} else { | ||
stack.push({ char: c, count: 1 }); | ||
} | ||
|
||
if (stack[stack.length - 1].count === k) { | ||
stack.pop(); | ||
} | ||
} | ||
|
||
return stack.reduce( | ||
(acc, { char, count }) => (acc += char.repeat(count)), | ||
'' | ||
); | ||
} |