forked from KnowledgeCenterYoutube/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
394_decode_string
58 lines (51 loc) · 1.43 KB
/
394_decode_string
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
Leetcode 394: Decode String
Detailed video explanation: https://youtu.be/yaCRdWMq4A4
=========================================================
C++:
----
class Solution {
string decodeString(string& s, int& i) {
string result;
while(i < s.length() && s[i] != ']'){
if(isdigit(s[i])){
int k = 0;
while(i < s.length() && isdigit(s[i]))
k = k*10 + s[i++] - '0';
i++;
string r = decodeString(s, i);
while(k-- > 0)
result += r;
i++;
} else
result += s[i++];
}
return result;
}
public:
string decodeString(string s) {
int i = 0;
return decodeString(s, i);
}
};
Java:
-----
class Solution {
int i = 0;
public String decodeString(String s) {
StringBuilder result = new StringBuilder();
while(i < s.length() && s.charAt(i) != ']'){
if(Character.isDigit(s.charAt(i))){
int k = 0;
while(i < s.length() && Character.isDigit(s.charAt(i)))
k = k*10 + s.charAt(i++) - '0';
i++;
String r = decodeString(s);
while(k-- > 0)
result.append(r);
i++;
} else
result.append(s.charAt(i++));
}
return result.toString();
}
}