我很难用JavaScript解决这个问题
您将获得一个由英文字母,标点符号,空白字符和括号组成的字符串。保证s中的括号形成常规括号序列。
你的任务是从最里面的一对开始,反转每对匹配括号中的字符串。
实施例
对于字符串“s = a(bc)de”,输出应为
reverseParentheses(s)=“acbde”。
输入/输出
[时间限制] 4000ms(js) [输入]字符串s
由英文字母,标点符号,空格字符和括号组成的字符串。保证括号形成常规括号序列。
约束:
5≤x.length≤55。
[输出]字符串
必须使用以下输入:
答案 0 :(得分:5)
def reverseParentheses(s):
for i in range(len(s)):
if s[i] == "(":
start = i
print (s[:start])
if s[i] == ")":
end = i
print (end)
return reverseParentheses(s[:start] + s[start+1:end][::-1] + s[end+1:])
return s
答案 1 :(得分:4)
这是一个解决方案:
var reverse = (str) => str.split('').reverse().join('');
var reverseParentheses = (s) => {
while (s.includes('(')) {
var l = s.lastIndexOf('(');
var r = s.indexOf(')', s.lastIndexOf('('));
s = s.slice(0, l) + reverse(s.slice(l + 1, r)) + (r + 1 === s.length ? s.slice(r, -1) : s.slice(r + 1));
}
return s;
};
答案 2 :(得分:2)
在JS中
使用正则表达式
function reverseInParentheses(s) {
if (s.match(/\([a-z]*\)/)) {
return reverseInParentheses(s.replace(/\([a-z]*\)/,
Array.from(s.match(/\([a-z]*\)/)[0].replace(/\(|\)/g,'')).reverse().join('')));
}
else return s;
}
简单方法:-
function reverseInParentheses(s) {
while (true) {
let c = s.indexOf(")");
if (c === -1) break;
let o = s.substring(0, c).lastIndexOf("(");
let start = s.substring(0, o);
let middle = s.substring(o + 1, c).split("").reverse().join("");
let end = s.substring(c + 1, s.length);
s = start + middle + end;
}
return s;
}
在Python中:
简单方法
def reverseInParentheses(s):
return eval('"' + s.replace('(', '"+("').replace(')', '")[::-1]+"') + '"')
使用堆栈方法
def reverseInParentheses(s):
stack = []
for x in s:
if x == ")":
tmp = ""
while stack[-1] != "(":
tmp += stack.pop()
stack.pop() # pop the (
for item in tmp:
stack.append(item)
else:
stack.append(x)
return "".join(stack)
在C ++中
简单方法:-
reverseString
函数将使用交换方法反转字符串,而reverseParentheses
函数将递归更新字符串。
string reverseString(string s){
for(int i = 0;i < s.length()/2;i++){
char t = s[s.length()-1-i];
s[s.length()-1-i] = s[i];
s[i] = t;
}
return s;
}
string reverseInParentheses(string s) {
int beg = 0;
int end = s.length() - 1;
for(int i = 0; i < s.length(); i++){
if(s[i] == '(')
beg = i;
if(s[i] == ')'){
end = i;
string temp = s.substr(beg + 1, end - beg - 1);
return reverseInParentheses(s.substr(0, beg) + reverseString(temp) + s.substr(end + 1));
}
}
return s;
}
答案 3 :(得分:0)
给定一个大小为n的字符串,这里是一个用C编写的递归代码,它以O(n)时间复杂度运行。 代码背后的想法是从字符串的开头开始,每次遇到开括号时,切换到其右括号并向后打印,然后在关闭括号后完成打印。 请注意,当您向后打印时,打开括号&#39; [&#39;被视为结束括号,反之亦然,以便关闭括号&#39;]&#39;。 最大字符串大小为100万,如果需要处理更长的字符串,则更改数组大小。
#include <stdio.h>
#include <string.h>
int n, other[1000010], stt[1000010];
char st[1000010];
void rec(int i, int dir) {
if(i >= n) return;
if(st[i] == '[') {
if(dir == 1) { // going right with '[' means opening
rec(other[i]-1, -dir); // go to the closing bracket and change direction
rec(other[i]+1, dir); // continue after the closing bracket after finishing
}
return;
}
if(st[i] == ']') {
if(dir == -1) { // going left with ']' means opening
rec(other[i]+1, -dir); // go to the closing bracket and change direction
rec(other[i]-1, dir); // continue after the closing bracket after finishing
}
return;
}
putchar(st[i]); // print character
rec(i+dir, dir); // continue same direction
}
int main() {
scanf("%s", st);
n = strlen(st);
for(int i=0, j, k=0; i<n; ++i) {
if(st[i] == '[') stt[k++] = i;
else if(st[i] == ']') {
j = stt[--k];
other[i] = j, other[j] = i;
}
}
rec(0, 1); // start from 0, with direction 1 (right)
return 0;
}
答案 4 :(得分:0)
这是我的JS解决方案,不使用正则表达式,初学者可能更容易理解。注释使代码不言自明,但想法是找到最后一个开始括号(如果表达式有嵌套括号),然后找到匹配的右括号,反转里面的文本并继续运行函数,直到字符串没有&# 39; t有任何更多的开括号(并且根据问题的定义,不再有右括号)。
function reverseParentheses(s) {
// We keep running the function while
// there's an opening bracket in the string
while (s.indexOf("(") !== -1) {
s = reverseP(s);
}
return s;
}
function reverseP(s) {
let len = s.length;
// We find the innermost/last opening bracket,
// and then we're going to find the matching closing bracket,
// which is the next closing bracket after the opening bracket
let openBracketInd = s.lastIndexOf("(");
// The characters before the opening bracket
let beforeBracket = s.slice(0, openBracketInd+1);
// The characters before the opening bracket
let afterBracket = s.slice(openBracketInd+1, len);
// To get the index of the closing bracket we add the
// characters before the bracket to the index of the first closing
// bracket in the string after the opening bracket
let closeBracketInd = beforeBracket.length + afterBracket.indexOf(")");
// Once we have the indexes, we're going to slice the string
// to remove the brackets
let firstPart = s.slice(0, openBracketInd);
let secondPart = s.slice(closeBracketInd+1, len);
let middle = s.slice(openBracketInd+1, closeBracketInd);
// We reverse the string between the brackets
middle = middle.split('').reverse().join('');
// And finally we join the parts and return the string
return firstPart+middle+secondPart;
}
&#13;
答案 5 :(得分:0)
这是一个使用正则表达式的递归解决方案,当正则表达式中存在匹配时,会调用reverseString方法,此匹配使用replace函数来替换被尊重的字符串。一旦被逆转,它会再次循环,直到没有更多的匹配..
function reverseParentheses(s) {
const reverseString = str => (str === '') ? '' : reverseString(str.substr(1)) + str.charAt(0);
const regex = /(\([\w\s\[\]!\.\,\;\:\?]*\))/g;
const iterator = a => {
if(regex.test(a)){
a=a.replace(regex, full => reverseString(full.replace(/[()]/g,'')));
return iterator(a);
} else return a;
}
return iterator(s);
}
答案 6 :(得分:0)
For Python 3 (not sure about Python 2), this code works. This does assume (as the problem on Code Fights states) that each parenthesis is a part of a pair.
def reverseParentheses(s):
from collections import Counter
for i in range(Counter(s)['(']):
one = s.rsplit('(',1)
two = one[1].split(')',1)
s = one[0]+two[0].replace(two[0],two[0][::-1]+two[1])
print(s)
return s
答案 7 :(得分:0)
def reverseParentheses(s)
0 while s.gsub!(/\(([^()]*)\)/) { $1.reverse }
return s
end
答案 8 :(得分:0)
F#中的解决方案:
let foldi fold first source =
source
|> List.fold (fun (prev,i) c -> (fold i prev c,i + 1)) (first,0)
|> fst
let reverseParentheses (s: string) =
let go pos (stack: list<list<char>>) (c: char) : list<list<char>> =
let fail () = failwithf "Parse error at pos %d, char '%c'." pos c
match c with
| '(' -> [] :: stack
| ')' ->
match stack with
| top :: next :: rest -> ((List.rev top @ next) :: rest)
| _ -> fail ()
| _ ->
match stack with
| top :: rest -> ((c :: top) :: rest)
| _ -> fail ()
s |> Seq.toList |> foldi go [[]] |> List.head |> List.rev |> List.toArray |> String
答案 9 :(得分:0)
在Java中: 简单方法
client.newCall(request).execute();
答案 10 :(得分:0)
使用JavaScript
function reverseInParentheses(inputString) {
let mainArr = inputString.split('');
let arrLength = mainArr.length;
let arr1 = [];
for(let i = 0; i < arrLength; i++) {
if(mainArr[i] != ')') {
arr1.push(mainArr[i]);
} else {
let temp = reverseSelectedString(arr1); // call function to reverse selected string
arr1 = arr1.splice(0, arr1.lastIndexOf("("));
arr1 = arr1.concat(temp);
}
}
return arr1.join('');
}
function reverseSelectedString(arrFirst) {
let arr2 = [];
let arrLength = arrFirst.length;
for(let j = arrLength; j >= 0; j--) {
if(arrFirst[j] != '(') {
arr2.push(arrFirst[j]);
} else {
break;
}
}
return arr2;
}
答案 11 :(得分:0)
在Javascript / node js中
//Regex for opening and closing parenthesis
const o_brc = /[\{\[\(]/g;
const c_brc= /[\}\]\)]/g;
const revPar = str => {
let top =-1;
let rev_str = [];
for(let i in str){
if(c_brc.test(str[i])){
const rev = [];
let j = i-1;
while(rev_str.length){
if(o_brc.test(rev_str[top])){
break;
}
rev.push( rev_str.pop());
top--;
}
rev_str.pop(); //pop out the opening brackets after reversing
top--;
rev_str = [...rev_str, ...rev];
top += rev.length; //increment the top upto rev.length
}
else{
rev_str.push(str[i]); //push to rev_str if not a closing bracket
top++;
}
}
console.log((rev_str.join('')));
}
答案 12 :(得分:0)
这是 C++ 中一个很好的直接答案
每当我们看到左括号时,我们就把索引压入堆栈,当我们找到一个结束的索引时,我们弹出最后一个索引并反转这两个索引之间的子串。然后我们删除额外的括号
string reverseInParentheses(string inputString) {
stack<int> index;
for (int i = 0 ; i < inputString.length(); i++){
if (inputString[i] == '('){
index.push(i);
}
if (inputString[i] == ')'){
reverse(inputString.begin()+ index.top(), inputString.begin()+i+1);
index.pop();
}
}
string s = "";
for (int i = 0; i < inputString.length();i++){
if (inputString[i] != '(' && inputString[i] != ')' )
s += inputString[i];
}
cout << s << endl;
return s;
}
答案 13 :(得分:0)
这是 Vahan 答案的修改版本,将正则表达式执行压缩为仅一个替换调用:
function reverseInParentheses(inputString) {
regex = /\(([^()]*)\)/i;
if (inputString.includes('(')) {
return reverseInParentheses(inputString.replace(regex, (_, $1) => $1.split('').reverse().join('')));
} else {
return inputString
}
}
答案 14 :(得分:-1)
public static String reverseParentheses(String s) {
StringBuilder sb = new StringBuilder();
char[] sArray = s.toCharArray();
int[] firstIndex = new int[s.length()]; //所有'('的索引
int[] lastIndex = new int[s.length()]; //所有')'的索引
int num = 0; // 表示遇到')'括号的次数
int count = 0; // 表示遇到"("括号的次数
boolean flag = false; //多种情况的判断
int index; //')'对应'('的位置
int countParentheses; //')'对应的'('的前面的括号个数
for (int i = 0; i < sArray.length; i++) {
if (sArray[i] == '(') {
//第一种情况
if (count == num && count != 0) {
flag = true;
} else if (count - num > 1 && num != 0) {//第三种情况
flag = true;
}
firstIndex[count] = i;
count++;
continue;
} else if (sArray[i] == ')') {
System.out.println("开始->遇到')':" + sb);
lastIndex[num] = i;
if (flag) {
index = count - num;
countParentheses = count + num;
flag = false;
} else {
//第二种情况
index = count - num - 1;
countParentheses = count - num;
}
System.out.println("截取初始位置:" + (firstIndex[index] - (countParentheses) + 1));
String s1 = sb.substring(firstIndex[index] - (countParentheses) + 1, lastIndex[num] - num - count);
System.out.println("截取出括号内的字符串:" + s1);
StringBuilder getString = new StringBuilder();
getString.append(s1);
getString.reverse();//反转
System.out.println("替代起始位置:" + (firstIndex[index] - (countParentheses) + 1));
System.out.println("替代的末位置:" + (lastIndex[num] - count - num));
System.out.println("字符串长度:" + getString.toString().length());
sb.replace(firstIndex[index] - (countParentheses) + 1, lastIndex[num] - count - num,
getString.toString().trim());
System.out.println("反转后:" + sb);
num++;
continue;
} else if (sArray[i] == ')' && count == num) {
} else {
sb.append(sArray[i]);
}
}
System.out.println("...." + sb);
return sb.toString();
}