Skip to content

Commit 09053e7

Browse files
Update and rename decode_string.py to decode_string.cpp
1 parent 99c5603 commit 09053e7

File tree

2 files changed

+71
-19
lines changed

2 files changed

+71
-19
lines changed

decode_string.cpp

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# Non recursive solution
2+
# class Solution:
3+
# def decodeString(self, s: str) -> str:
4+
# prevStr, currStr, currNum = '', '', 0
5+
# decode, ans = [], ''
6+
# for ch in s:
7+
# if ch == '[':
8+
# decode.append(currNum)
9+
# decode.append(currStr)
10+
# currStr = ''
11+
# currNum = 0
12+
# elif ch == ']':
13+
# prevStr = decode.pop()
14+
# digit = decode.pop()
15+
# currStr = prevStr + (currStr * digit)
16+
# elif ch.isdigit():
17+
# currNum = currNum * 10 + int(ch)
18+
# else:
19+
# currStr += ch
20+
# return currStr
21+
22+
23+
class Solution {
24+
25+
private:
26+
string decodeStringHelper(int &position, string s) {
27+
28+
int num = 0; //keep track of current integer
29+
string word = ""; //current word
30+
31+
for(;position<s.size(); ++position) {
32+
33+
//if we encounter a [ - treat it as a start of subproblem and recurse. After this repeat the substr formed from recursion num times
34+
// ] - end of subproblem, return word
35+
//if we encounter a number - form the num
36+
//if we encounter a character - just add it to the current word
37+
38+
char currChar = s[position];
39+
if(currChar == '[') {
40+
string currStr = decodeStringHelper(++position, s);
41+
for(; num > 0; num--) word += currStr;
42+
}
43+
44+
else if(currChar >= '0' and currChar <= '9') {
45+
num = num * 10 + currChar - '0';
46+
}
47+
48+
else if(currChar == ']') {
49+
return word;
50+
}
51+
52+
else {
53+
word += currChar;
54+
}
55+
56+
}
57+
return word;
58+
}
59+
60+
public:
61+
/*
62+
Recursive solution - more intuitive
63+
*/
64+
string decodeString(string s) {
65+
66+
int position = 0;
67+
return decodeStringHelper(position, s);
68+
}
69+
};
70+
71+

decode_string.py

Lines changed: 0 additions & 19 deletions
This file was deleted.

0 commit comments

Comments
 (0)