FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
leetcode-solutions/decode_string.cpp at master · avidLearnerInProgress/leetcode-solutions · GitHub
avidLearnerInProgress
/
leetcode-solutions
Public
Notifications
You must be signed in to change notification settings
Fork
5
Star
19
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
leetcode-solutions
/
decode_string.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
71 lines (56 loc) · 2.1 KB
Breadcrumbs
leetcode-solutions
/
decode_string.cpp
Copy path
File metadata and controls
71 lines (56 loc) · 2.1 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//
# Non recursive solution
//
# class Solution:
//
# def decodeString(self, s: str) -> str:
//
# prevStr, currStr, currNum = '', '', 0
//
# decode, ans = [], ''
//
# for ch in s:
//
# if ch == '[':
//
# decode.append(currNum)
//
# decode.append(currStr)
//
# currStr = ''
//
# currNum = 0
//
# elif ch == ']':
//
# prevStr = decode.pop()
//
# digit = decode.pop()
//
# currStr = prevStr + (currStr * digit)
//
# elif ch.isdigit():
//
# currNum = currNum * 10 + int(ch)
//
# else:
//
# currStr += ch
//
# return currStr
class
Solution
{
private:
string
decodeStringHelper
(
int
&position, string s) {
int
num =
0
;
//
keep track of current integer
string word =
"
"
;
//
current word
for
(;position<s.
size
(); ++position) {
//
if we encounter a [ - treat it as a start of subproblem and recurse. After this repeat the substr formed from recursion num times
//
] - end of subproblem, return word
//
if we encounter a number - form the num
//
if we encounter a character - just add it to the current word
char
currChar = s[position];
if
(currChar ==
'
[
'
) {
string currStr =
decodeStringHelper
(++position, s);
for
(; num >
0
; num--) word += currStr;
}
else
if
(currChar >=
'
0
'
and
currChar <=
'
9
'
) {
num = num *
10
+ currChar -
'
0
'
;
}
else
if
(currChar ==
'
]
'
) {
return
word;
}
else
{
word += currChar;
}
}
return
word;
}
public:
/*
Recursive solution - more intuitive
*/
string
decodeString
(string s) {
int
position =
0
;
return
decodeStringHelper
(position, s);
}
};
Back
|
FazBrowse Home
|
New Git URL