題目
Given an encoded string, return it's decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].
答案
class Solution {
public int pos_matching_right_paren(String s, int left_paren_pos) {
int count = 0;
for(int i = left_paren_pos; i < s.length(); i++) {
char c = s.charAt(i);
if(c == '[') count++;
else if(c == ']') count--;
if(c == ']' && count == 0) return i;
}
return -1;
}
public String decodeString(String s) {
if(s.length() <= 0) return "";
// Find first char絮重, could only be digit or letter
char first_char = s.charAt(0);
// Digit
if(Character.isDigit(first_char)) {
// Get the number
int last_digit_idx = 0;
for(int i = 0; i < s.length(); i++) {
if(Character.isDigit(s.charAt(i)))
last_digit_idx = i;
else
break;
}
int number = Integer.parseInt(s.substring(0, last_digit_idx + 1));
int left_paren_pos = s.indexOf('[');
int right_paren_pos = pos_matching_right_paren(s, left_paren_pos);
String str = s.substring(left_paren_pos + 1, right_paren_pos);
String decoded_str = decodeString(str);
String repeat_str = "";
for(int i = 0; i < number; i++) repeat_str += decoded_str;
return repeat_str + decodeString(s.substring(right_paren_pos + 1));
}
// Letter
else {
int left_paren_pos = s.indexOf('[');
if(left_paren_pos == -1) return s;
int digit_index = 0;
for(int i = 0; i < s.length(); i++) {
if(Character.isDigit(s.charAt(i))) {
digit_index = i;
break;
}
}
return s.substring(0, (digit_index == -1)?s.length() : digit_index) + decodeString(s.substring(digit_index));
}
}
}