3ms Java Solution by re-construction the String during recursion


  • 0
    Z
    //rebuild the String if recursion happened
    public Stack<Integer> stack = new Stack<>();
    public StringBuilder sb = new StringBuilder();
    public String decodeString(String s) {
    	int l = 0;
    	int factor = 0;
    	int start = 0;
    	int end = 0;
    	int digitS = 0;
    	for(int i = 0; i < s.length(); i++){
    		if(s.charAt(i) >= '0' && s.charAt(i) <= '9'){
    			factor = factor * 10 + ((int)s.charAt(i) - 48);
    			if(factor <= 9){
    				digitS = i;
    			}
    		}
    		
    		else if(s.charAt(i) == '['){
    			l++;
    			start = i + 1;
    			stack.push(factor);
    			factor = 0;
    		}
    		
    		else if(s.charAt(i) == ']'){
    			end = i;
    			l--;
    			if(l == 0){
    				factor = stack.pop();
    				while(factor > 0){
    					sb.append(s.substring(start, end));
    					factor--;
    				}
    			}
    			else{	// if(l != 0)
    				factor = stack.pop();
    				StringBuilder tmp = new StringBuilder();
    				while(factor > 0){
    					tmp.append(s.substring(start, end));
    					factor--;
    				}
    
    				String t = s.substring(0, digitS) + tmp.toString() + s.substring(end + 1, s.length());
    				decodeString(t);//input the new String here
    				//successfully change 3[a2[c]] to 3[acc]
    				break;
    			}
    		}
    		else{
    			if(l > 0){
    				factor = 0;
    			}
    			else{
    				sb.append(s.charAt(i));
    			}
    		}
        }
        return sb.toString();
    }

  • 0
    S

    I think you'd better comment it in English rather xie zhong wen :)


  • 0
    Z

    Sorry man, I just updated the comment in EN.


Log in to reply
 

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