clear simple recursive solution


  • 0
    W
    public class Solution {
        public String decodeString(String s) {
            if (s == null || s.length() == 0) return ""; 
            for (int i = 0; i < s.length(); i++) {
                // first number in s
                if (Character.isDigit(s.charAt(i))) {
                    // find matched repeat part 
                    int start = s.indexOf("[", i); 
                    int end = start+1;
                    int count = 1; 
                    while (count != 0) {
                        char c = s.charAt(end); 
                        if (c == '[') count++; 
                        else if (c == ']') count--;
                        end++;
                    }
                    
                    //construct repet part; 
                    int repeatCount = Integer.parseInt(s.substring(i, start)); 
                    String repeatUnit = decodeString(s.substring(start+1, end-1)); 
                    String repeatPart = ""; 
                    for (int j = 0; j < repeatCount; j++) {
                        repeatPart = repeatPart + repeatUnit; 
                    }
                    return s.substring(0, i) + repeatPart + decodeString(s.substring(end));
                }
            }
            return s;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.