Java short solution


  • 0
    C

    Here's one quick solution.

    Search for all occurrences of #[a-z] in s, then build new partby repeating the string that has been found between [and ] and use it to replace matched group. Loop until we've replaced everything in s.

    public String decodeString(String s) { // shorter but less optimized REGEX
            Matcher matcher = Pattern.compile("(\\d*)\\[([a-z]*)\\]").matcher(s);
            while (matcher.find()) {
                StringBuffer sb = new StringBuffer();
                String part = new String(new char[Integer.parseInt(matcher.group(1))]).replace("\0", matcher.group(2));
                matcher.appendReplacement(sb, part).appendTail(sb);
                matcher.reset(s = sb.toString());
            }
            return s;
        }
    

Log in to reply
 

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