File tree Expand file tree Collapse file tree 1 file changed +70
-0
lines changed Expand file tree Collapse file tree 1 file changed +70
-0
lines changed Original file line number Diff line number Diff line change 1+ // Time: O(n)
2+ // Space: O(h)
3+
4+ // stack
5+ function jsonParse ( str : string ) : any {
6+ let stk = [ ] ;
7+ let result = null ;
8+ let k = null ;
9+ for ( let i = 0 ; i < str . length ; i ++ ) {
10+ if ( str [ i ] === "," || str [ i ] === ":" ) {
11+ continue ;
12+ }
13+ if ( str [ i ] === '{' || str [ i ] === '[' ) {
14+ let v = str [ i ] === '{' ? { } : [ ] ;
15+ if ( result !== null ) {
16+ if ( k !== null ) {
17+ result [ k ] = v ;
18+ k = null ;
19+ } else {
20+ result . push ( v ) ;
21+ }
22+ stk . push ( result ) ;
23+ }
24+ result = v ;
25+ } else if ( str [ i ] === '}' || str [ i ] === ']' ) {
26+ if ( stk . length !== 0 ) {
27+ result = stk . pop ( ) ;
28+ }
29+ } else {
30+ let v ;
31+ if ( str [ i ] === '-' || ( '0' <= str [ i ] && str [ i ] <= '9' ) ) {
32+ let j = i ;
33+ while ( i + 1 < str . length &&
34+ ( str [ i + 1 ] === '-' || ( '0' <= str [ i + 1 ] && str [ i + 1 ] <= '9' ) || str [ i + 1 ] === '.' ) ) {
35+ i ++ ;
36+ }
37+ v = Number ( str . substring ( j , i + 1 ) ) ;
38+ } else if ( str [ i ] === '"' ) {
39+ let j = i + 1 ;
40+ while ( i + 1 < str . length && str [ i + 1 ] !== '"' ) {
41+ i ++ ;
42+ }
43+ v = str . substring ( j , i + 1 ) ;
44+ i ++ ;
45+ } else {
46+ if ( i + 3 < str . length && str . substring ( i , i + 4 ) === "true" ) {
47+ v = true ;
48+ i += 3 ;
49+ } else if ( i + 4 < str . length && str . substring ( i , i + 5 ) === "false" ) {
50+ v = false ;
51+ i += 4 ;
52+ } else {
53+ v = null ;
54+ i += 3 ;
55+ }
56+ }
57+ if ( result === null ) {
58+ result = v ;
59+ } else if ( str [ i + 1 ] === ":" ) {
60+ k = v ;
61+ } else if ( k !== null ) {
62+ result [ k ] = v ;
63+ k = null ;
64+ } else {
65+ result . push ( v ) ;
66+ }
67+ }
68+ }
69+ return result ;
70+ } ;
You can’t perform that action at this time.
0 commit comments