forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
5db6d7d
commit 702d63f
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
class Solution { | ||
|
||
int index = 0; | ||
|
||
public String decodeString(String s) { | ||
|
||
StringBuilder decoded = new StringBuilder(); | ||
while (index < s.length() && s.charAt(index) != ']') { | ||
|
||
// character is a letter of encoded | ||
if (!Character.isDigit(s.charAt(index))) decoded.append(s.charAt(index++)); | ||
|
||
// character is number or [ ] | ||
else { | ||
int k = 0; | ||
|
||
// case: number | ||
while (index < s.length() && Character.isDigit(s.charAt(index))) k = k * 10 + s.charAt(index++) - '0'; | ||
|
||
// case: [ | ||
index++; | ||
String answer = decodeString(s); | ||
|
||
// case: ] | ||
index++; | ||
|
||
// add k*encoded to decoded | ||
while (k-- > 0) decoded.append(answer); | ||
} | ||
} | ||
return new String(decoded); | ||
} | ||
} |