Java 从最里面的括号中反转字符串,并在反转时删除括号
我正在codefights.com上练习编码。现在面临这个问题。 字符串由字母、标点符号、空格和括号组成。 支架将如下所示()。任务是反转包含在 每对匹配括号,从最里面的一对开始。结果字符串 不应包含任何括号。一些例子如下:Java 从最里面的括号中反转字符串,并在反转时删除括号,java,string,Java,String,我正在codefights.com上练习编码。现在面临这个问题。 字符串由字母、标点符号、空格和括号组成。 支架将如下所示()。任务是反转包含在 每对匹配括号,从最里面的一对开始。结果字符串 不应包含任何括号。一些例子如下: 输入:“a(bc)de” 输出:“acbde” 输入:“a(bcdefghijkl(mno)p)q” 输出:“apmnolkjihgfedcbq” 输入:“abc(cba)ab(bac)c” 输出:“ABCABC” 对于前2个示例,我的代码运行良好。但对于第三个,它给出了S
输入:“a(bc)de”
输出:“acbde”
输入:“a(bcdefghijkl(mno)p)q”
输出:“apmnolkjihgfedcbq”
输入:“abc(cba)ab(bac)c”
输出:“ABCABC”
对于前2个示例,我的代码运行良好。但对于第三个,它给出了StringIndexOutOfBoundsException,如下所示:
线程“main”java.lang.StringIndexOutOfBoundsException中的异常:字符串索引超出范围:-4
位于java.lang.AbstractStringBuilder.substring(AbstractStringBuilder.java:872)
位于java.lang.StringBuilder.substring(StringBuilder.java:72)
在codefight.arcade.intro.level_3.ReverseParentheses.ReverseParentheses(ReverseParentheses.java:45)
在codefaight.arcade.intro.level_3.ReverseParentheses.main(ReverseParentheses.java:16)
在sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法)处
在sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)中
在sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)中
位于java.lang.reflect.Method.invoke(Method.java:601)
在com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
这是我的任务代码>>>
public static void main(String[] args) {
String s = "abc(cba)ab(bac)c";
String outputString = reverseParentheses(s);
System.out.print(outputString);
}
public static String reverseParentheses(String str) {
StringBuilder s = new StringBuilder(str);
String prnth1 = "(";
String prnth2 = ")";
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
for (int i=0; i<s.length(); i++) {
if (s.charAt(i) == prnth1.charAt(0)) {
list1.add(i);
}
}
for (int i=0; i<s.length(); i++) {
if (s.charAt(i) == prnth2.charAt(0)) {
list2.add(i);
}
}
Collections.reverse(list1);
for (int i=0; i<list1.size(); i++) {
int firstIndex = list1.get(i);
int lastIndex = list2.get(i);
String ascString = s.substring(firstIndex + 1, lastIndex);
String reverseString = new StringBuilder(ascString).reverse().toString();
s = new StringBuilder(s.toString().replace(s.substring(firstIndex + 1, lastIndex), reverseString));
}
s = new StringBuilder(s.toString().replaceAll("\\(", "").replaceAll("\\)",""));
return s.toString();
}
publicstaticvoidmain(字符串[]args){
字符串s=“abc(cba)ab(bac)c”;
String outputString=reverseParentheses;
系统输出打印(输出字符串);
}
公共静态字符串反转参数(字符串str){
StringBuilder s=新的StringBuilder(str);
字符串prnth1=“(”;
字符串prnth2=“)”;
ArrayList list1=新的ArrayList();
ArrayList list2=新的ArrayList();
对于(int i=0;我将谈到堆栈溢出!看起来您需要学习使用调试器。请自己解决一些问题。如果以后仍有问题,请随时返回以演示您的问题。@JoeC感谢您的回答。这可能是一个愚蠢的逻辑错误,我有IndexOutOfBounce错误。我需要帮助在这里构建我的逻辑。也许,但堆栈溢出不是一种调试服务。请在调试器中花一些时间查找故障所在,如果您无法理解故障原因,请随意询问。(我将首先询问为什么使用索引-4
调用子字符串
)。