java 16ms with regex recursive


  • 0
    D
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class Solution {
        Pattern p = Pattern.compile("\\[[a-z]*\\]");
    
        public String decodeString(String s) {
            Matcher m = p.matcher(s);
            String sub = "";
            if(!m.find()){
                return s;
            }else{
                sub = m.group();
            }
            String content = sub.substring(1,sub.length()-1);
            String pattern ="\\d*(?=\\["+content+"\\])";
            Pattern numberCompile = Pattern.compile(pattern);
            Matcher numberMatcher = numberCompile.matcher(s);
            int count = 0 ;
            if(numberMatcher.find()){
                 count = Integer.valueOf(numberMatcher.group());
            }
            String instend = "";
            for(int i=0;i<count;i++){
                instend += content;
            }
            return decodeString(s.replace(count+sub,instend));
        }
    }
    

  • 0
    D
    public class DecodeString {
        Pattern p = Pattern.compile("\\[[a-z]*\\]");
    
        public String decodeString(String s) {
            Matcher m = p.matcher(s);
            String sub = "";
            if(!m.find()){
                return s;
            }else{
                sub = m.group();
            }// sub = [c]
            String content = sub.substring(1,sub.length()-1);// sub = c
            String pattern ="\\d*(?=\\["+content+"\\])";  // rex \d*\[c\]
            Pattern numberCompile = Pattern.compile(pattern);
            Matcher numberMatcher = numberCompile.matcher(s);
            int count = 0 ;
            if(numberMatcher.find()){
                 count = Integer.valueOf(numberMatcher.group()); //find repeat number
            }
            String instend = ""; //repeat content
            for(int i=0;i<count;i++){
                instend += content;
            }
            return decodeString(s.replace(count+sub,instend));// 3[acc]
        }
    

Log in to reply
 

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