Recursive Java solution without using stack


  • 1
    S
    public String decodeString(String s) {
            char[] cs = s.toCharArray();
    	StringBuilder sb = new StringBuilder();
    	int time = 0, start = 0, brackets = 0;
    
    	for (int i = 0; i<cs.length; i++) {
    		if (cs[i]-'0'>=0 && cs[i]-'0'<=9 && brackets == 0) {
    			time = time*10+cs[i]-'0';
    		}else if (cs[i] == '[') {
    			if (++brackets == 1) start = i+1;
    		}else if(cs[i] == ']' && --brackets == 0){
    			for (int j = 0; j < time; j++) {
    				sb.append(decodeString(s.substring(start, i)));
    			}
    			time = 0;
    		}else if (brackets == 0)sb.append(cs[i]);
    	}
    	return sb.toString();
    }
    

Log in to reply
 

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