本文介绍了反括号 - Codefights的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难用 JavaScript 解决这个问题

给定一个字符串 s,它由英文字母、标点符号、空格字符和括号组成.保证s中的括号形成一个正则的括号序列.

You are given a string s that consists of English letters, punctuation marks, whitespace characters and brackets. It is guaranteed that the brackets in s form a regular bracket sequence.

您的任务是从最里面的括号开始反转每对匹配括号中的字符串.

Your task is to reverse the strings in each pair of matching parenthesis, starting from the innermost one.

示例

对于字符串s = a(bc)de,输出应该是

For string s = a(bc)de the output should be

reverseParentheses(s) = "acbde".

输入/输出

[time limit] 4000ms (js)
[input] string s

由英文字母、标点符号、空白字符和括号组成的字符串.保证括号形成正则括号序列.

A string consisting of English letters, punctuation marks, whitespace characters and brackets. It is guaranteed that parenthesis form a regular bracket sequence.

约束:

5 ≤ x.length ≤ 55.

[输出] 字符串

它必须使用以下输入:

  1. s: a(bcdefghijkl(mno)p)q 预期输出:apmnolkjihgfedcbq
  2. s: co(de(fight)s) 预期输出: cosfighted

推荐答案

function reverseParentheses(s) {
    if (s.includes('(')){
        return reverseParentheses(reverseOnce(s));
    } else {
        return s;
    }
}

function reverseOnce(s){
    var regexp = /\(([^()]*)\)/i;
    var subStr = regexp.exec(s)[1];
    subStr = subStr.split('').reverse().join('');
    return s.replace(regexp, subStr)
}

这篇关于反括号 - Codefights的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 15:48
查看更多