File tree 2 files changed +46
-0
lines changed
2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ } ) ;
You can’t perform that action at this time.
0 commit comments