Java solution using regular expression


  • 0
    F

    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(matcher.group(1));
                    for (int i = 0; i < n; i++) {
                        stringBuilder.append(matcher.group(2));
                    }
                    matcher.appendReplacement(stringBuffer, stringBuilder.toString());
                }
                matcher.appendTail(stringBuffer);
            }
            return stringBuffer.toString();
        }
    }

Log in to reply
 

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