Java solution using regular expression

  • 0

    Since I am not very familar with regular expression, this solution may not be very good, just for share.

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class Solution {
        public String decodeString(String s) {
            Pattern pattern = Pattern.compile("(\\d+)\\[([a-z]*)\\]");
            Matcher matcher;
            StringBuffer stringBuffer = new StringBuffer(s);
            while (stringBuffer.indexOf("[") >= 0) {
                matcher = pattern.matcher(stringBuffer);
                stringBuffer = new StringBuffer();
                while (matcher.find()) {
                    StringBuilder stringBuilder = new StringBuilder();
                    int n = Integer.valueOf(;
                    for (int i = 0; i < n; i++) {
                    matcher.appendReplacement(stringBuffer, stringBuilder.toString());
            return stringBuffer.toString();

Log in to reply

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