Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions rust/0394-decode-string.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
impl Solution {
pub fn decode_string(s: String) -> String {
let mut stack = vec![];

for ch in s.chars() {
if ch != ']' {
stack.push(ch.to_string());
} else {
let mut substr = String::new();
while stack.last() != Some(&"[".to_string()) {
substr = stack.pop().unwrap().to_string() + &substr;
}
stack.pop();

let mut multiplier = String::new();
while !stack.is_empty() && stack.last().unwrap().parse::<i32>().is_ok() {
multiplier = stack.pop().unwrap().to_string() + &multiplier;
}

stack.push(substr.repeat(multiplier.parse::<usize>().unwrap()));
}
}
stack.join("")
}
}
26 changes: 26 additions & 0 deletions typescript/0394-decode-string.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
function decodeString(s: string): string {
let stack: string[] = [];

for (let char of s) {
if (char !== ']') {
stack.push(char);
} else {
let substr: string = '';
while (stack[stack.length - 1] !== '[') {
substr = stack.pop() + substr;
}
stack.pop();

let multiplier: string = '';
while (
stack.length !== 0 &&
Number.isInteger(+stack[stack.length - 1])
) {
multiplier = stack.pop() + multiplier;
}

stack.push(substr.repeat(+multiplier));
}
}
return stack.join('');
}