Java 3ms using StringBuilder


  • 0
    Z
    public String decodeString(String s) {
        StringBuilder sBuilder=new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
    		if (s.charAt(i)!=']') {
    			sBuilder.append(s.charAt(i));
    		}
    		else sBuilder=decodeBuilder(sBuilder);
    	}
        return sBuilder.toString();
    }
    
    private StringBuilder decodeBuilder(StringBuilder sBuilder) {
    	// TODO Auto-generated method stub
    	int left=sBuilder.lastIndexOf("[");
    	String repeat=sBuilder.substring(left+1);
    	int notChar=left-1;
    	for (; notChar >= 0; notChar--) {
    		if (sBuilder.charAt(notChar)>='0'&&sBuilder.charAt(notChar)<='9') {	
    		}
    		else {break;}
    	}
    	notChar++;
    	int times=Integer.parseInt(sBuilder.substring(notChar,left));
    	sBuilder.delete(notChar, sBuilder.length());
    	for (int i = 0; i < times; i++) {
    		sBuilder.append(repeat);
    	}
    	return sBuilder;
    }

Log in to reply
 

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