Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 4c3db4c

Browse filesBrowse files
author
Kohei Asai
authored
394. Decode String (#142)
1 parent d2a1b7f commit 4c3db4c
Copy full SHA for 4c3db4c

File tree

Expand file treeCollapse file tree

2 files changed

+46
-0
lines changed
Filter options
Expand file treeCollapse file tree

2 files changed

+46
-0
lines changed

‎solutions/decode_string.ts

Copy file name to clipboard
+33Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// 394. Decode String
2+
// https://leetcode.com/problems/decode-string/
3+
export default function decodeString(s: string): string {
4+
let decoded = "";
5+
let repeat = 0;
6+
let brackets = 0;
7+
let bracketFrom = 0;
8+
9+
for (let i = 0; i < s.length; ++i) {
10+
if (s[i] === "[") {
11+
brackets += 1;
12+
13+
if (brackets === 1) {
14+
bracketFrom = i;
15+
}
16+
} else if (s[i] === "]") {
17+
brackets -= 1;
18+
19+
if (brackets === 0) {
20+
decoded += decodeString(s.substring(bracketFrom + 1, i)).repeat(repeat);
21+
repeat = 0;
22+
}
23+
} else if (brackets === 0) {
24+
if (s.charCodeAt(i) >= 48 && s.charCodeAt(i) <= 57) {
25+
repeat = repeat * 10 + s.charCodeAt(i) - 48;
26+
} else {
27+
decoded += s[i];
28+
}
29+
}
30+
}
31+
32+
return decoded;
33+
}

‎solutions/decode_string_test.ts

Copy file name to clipboard
+13Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { test } from "https://deno.land/std/testing/mod.ts";
2+
import { assertStrictEq } from "https://deno.land/std/testing/asserts.ts";
3+
import decodeString from "./decode_string.ts";
4+
5+
test("394. Decode String", () => {
6+
assertStrictEq(decodeString("3[a]2[bc]"), "aaabcbc");
7+
assertStrictEq(decodeString("3[a2[c]]"), "accaccacc");
8+
assertStrictEq(decodeString("2[abc]3[cd]ef"), "abcabccdcdcdef");
9+
assertStrictEq(
10+
decodeString("a2[b3[c4[d]e]]f3[g]h"),
11+
"abcddddecddddecddddebcddddecddddecddddefgggh"
12+
);
13+
});

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.