zoukankan      html  css  js  c++  java
  • codewars--js--Simple string expansion+ repeat(),includes()方法

    问题描述:

    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!

    我的思路:

    基本上我解题的步骤就是自己手动的步骤,惭愧惭愧!·

    先找到最里面的括号,然后按要求扩展。

    当(前没有数字的时候,直接将该对括号去掉,然后继续做。

    我的答案:

    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;
    }

    优秀答案:

    (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()返回一个新的字符串对象,它的值等于重复了指定次数的原始字符串。

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

    (2)

    哈哈哈!

  • 相关阅读:
    SE -- IO
    SE -- 多线程
    SE -- 继承
    SE -- 面对对象
    SE -- 数组
    Modern Operating System --- Chap 5.5 Clocks
    Operating System: Three Easy Pieces --- Paging: TLB (Note)
    Operating System: Three Easy Pieces --- Process (Note)
    Some Interesting Websites and Blogs
    Implement a System Call in Kernel 3.10.56 (X86_64)
  • 原文地址:https://www.cnblogs.com/hiluna/p/8909514.html
Copyright © 2011-2022 走看看