从最内侧括号中反转字符串,并在反向时删除括号

时间:2017-07-11 20:10:34

标签: java string

我在codefights.com上练习一些编码。现在面临这个问题。 字符串由字母,标点符号,空格和括号组成。 括号将是这样的()。任务是反转包含在中的字符串 每对匹配的括号,从最里面的一对开始。结果字符串 不应包含任何括号。一些例子如下:

input : "a(bc)de" output : "acbde"

input : "a(bcdefghijkl(mno)p)q" output : "apmnolkjihgfedcbq"

input : "abc(cba)ab(bac)c" output : "abcabcabcabc"

对于前两个示例,我的代码工作正常。但是对于第三个,它给出了StringIndexOutOfBoundsException,如下所示:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -4 at java.lang.AbstractStringBuilder.substring(AbstractStringBuilder.java:872) at java.lang.StringBuilder.substring(StringBuilder.java:72) at codefight.arcade.intro.level_3.ReverseParentheses.reverseParentheses(ReverseParentheses.java:45) at codefight.arcade.intro.level_3.ReverseParentheses.main(ReverseParentheses.java:16) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at 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();
}

0 个答案:

没有答案