codewars--js--Simple string expansion+ repeat(),includes()方法

Problem Description:

Consider the following expansion:

solve("3(ab)") = "ababab" -- "ab" repeats 3 times
solve("2(a3(b))" = "abbbabbb" -- "a3(b)" == "abbb" repeats twice. 

Given a string, return the expansion of that string.

Input will consist of only lowercase letters and numbers in valid parenthesis. There will be no letters or numbers after the last closing parenthesis.

More examples in test cases.

Good luck!

 

My train of thought:

Basically, the steps I take to solve the problem are my own manual steps, I am ashamed! ·

Find the innermost parenthesis first, then expand as required.

When (there is no number before, just remove the pair of brackets, and then continue.

my answer:

function solve(str){
      
      while(str.indexOf("(")!=-1){
        var a=[];
        var b=[];
        var s=str.split("");
        var left=str.lastIndexOf("(");
        var right=str.indexOf(")");
        if(/[1-9]/.test(s[left-1])){
          b=str.slice(left+1,right);
          for(var j=0;j<parseInt(s[left-1]);j++){
            a.push(b);
          }  //可换成 a=b.repeat(parseInt(s[left-1]);
          s.splice(left-1,right-left+2,a.join(""));  
          }else{
          s.splice(left,1,"");
          s.splice(right,1,"");
          
        }
str=s.join("");
    }
  return str;
}

 

Excellent answer:

(1)

function solve(s) {
  while (s.includes('(')) {
    s = s.replace(/\d?\((\w*)\)/,(m,a)=>a.repeat(+m[0]||1));
  }
  return s;
}

(2)

const solve = s => s.includes`(` ? solve(s.replace(/(\d*)\(([a-z]+)\)/, (_,a,b)=> b.repeat(+a||1))): s;

 

 

js

(1) repeat() returns a new string object whose value is equal to the original string repeated the specified number of times.

"acb".repeat(3); // "acbacbacb"

(2)

Hahaha!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324652923&siteId=291194637