Skip to content

Commit

Permalink
Create 0394-decode-string.java
Browse files Browse the repository at this point in the history
  • Loading branch information
sarahtang7 authored Mar 24, 2023
1 parent 5db6d7d commit 702d63f
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions java/0394-decode-string.java
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);
}
}

0 comments on commit 702d63f

Please sign in to comment.