首页 > 解决方案 > 试图找到一个返回两个括号之间的字符串的递归方法

问题描述

字符串中只有一对括号并且它们是平衡的,我不能使用内部用于循环的方法,例如包含等,并且禁止使用正则表达式。

这是我想出的代码,但它总是显示错误。

    public static String getParenthesis(String str) {
    int first = 1 , last = str.length()-2;
        if(str.charAt(0) =='(')
        {
            first = 0;
        }
            
        if (str.charAt(str.length()-1) == ')')
            last++;
        if(str.charAt(str.length()-1) == ')'&& str.charAt(0)=='(')
        return str;
        
        return getParenthesis(str.substring(first, last));

}*/

标签: javarecursion

解决方案


因此,例如,给定一个输入字符串:

Paren(thesis)String

你想打印:

thesis

让我们将此字符串视为字符数组并引入两个索引:firstsize

    first                                  size (== str.length())
      |                                     |_
str:  P a r e n ( t h e s i s ) S t r i n g |_|

您想要递增 first直到到达左大括号 - (

你想递减 size 直到你到达正确的大括号 - )

剩下的只是适当管理索引以满足String's substring()

public static String getParenthesis(String str) {
    int first = 0, size = str.length();
    if (str.charAt(first) != '(')
        return getParenthesis(str.substring(first + 1, size));
    if (str.charAt(size - 1) != ')')
        return getParenthesis(str.substring(first, size - 1));
    return str.substring(first + 1, size - 1);
}

推荐阅读