用递归方法提取外括号之间的sudstring的方法

问题描述 投票:0回答:0

因此,我正在研究一种递归方法清洁,该方法可以在没有括号本身的情况下提取弦的最外层括号内的子字符串。 该方法按预期工作,但在诸如“ 123(45))之类的情况下省略了闭合括号”,我希望结果为“ 45)”。 我的目标:该方法应返回一个仅包含最外层括号内的substring的新字符串,而无需括号本身。如果没有有效的括号,该方法应返回一个空字符串。

约束是:

不使用循环,只能使用递归。

    您只能使用以下字符串方法:charat,equals,engens,substring和iSempty。
  • 输入字符串保证是非零的。
  • public static void main(String[] args) { String seq = "1(234)67"; System.out.println(clean(seq)); // Expected output: "234" System.out.println(clean("123(45))")); // Expected output: "45)" System.out.println(clean("x)")); // Expected output: "" System.out.println(clean(")x(")); // Expected output: "" } public static String clean(String seq) { if (seq.isEmpty()) { return ""; } // If the first character is not '(', remove all characters before it if (seq.charAt(0) != '(') { return clean(seq.substring(1)); } int depth = 0; int startIdx = -1; int endIdx = -1; // Recursively traverse the string to find the outer parentheses for (int i = 0; i < seq.length(); i++) { char ch = seq.charAt(i); if (ch == '(') { if (depth == 0) { startIdx = i; // Mark the start of the outer parenthesis } depth++; } else if (ch == ')') { depth--; if (depth == 0) { endIdx = i; // Mark the end of the outer parenthesis break; } } } // If an outer parenthesis is found, return the substring without the parentheses if (startIdx != -1 && endIdx != -1) { return seq.substring(startIdx + 1, endIdx); // Return the content inside the parentheses } // Return an empty string if no valid parentheses are found return ""; } }

  • 电流输出:
  • clean("1(234)67") -> "234" clean("123(45))") -> "45" clean("x)") -> "" clean(")x(") -> ""

  • 指望输出:
clean("1(234)67") -> "234"
clean("123(45))") -> "45)"
clean("x)") -> ""
clean(")x(") -> ""

当字符串具有有效的括号时,该函数按预期工作,但是对于字符串“ 123(45))”,我需要输出为“ 45)”(包括关闭括号))。但是,当前的实现返回“ 45”,而无需结束括号。

i我尝试修改该方法,但我不确定如何正确处理未完全封闭的括号中的情况。当该方法是最外面括号的一部分时,该方法仍应包括闭合括号。
因此,基本上,如何修改代码以确保“ 123(45))”?
任何帮助都非常感谢!

我提出了不同的路径:

public static String clean( String seq ) { if( seq.isEmpty() ) { return ""; } // we take the first occurrence of “(” and the last occurrence of “)”. int iniPos = seq.indexOf( "(" ); int finPos = seq.lastIndexOf( ")" ); // if both are different from “-1” and **iniPos** is less than **finPos** // we recursion, passing as parameter, the string contained between both, if( iniPos != -1 && finPos != - 1 && iniPos < finPos ) { System.out.println( " -> " + seq.substring( iniPos + 1, finPos ) ); return clean( seq.substring( iniPos + 1, finPos )); } else { // if the **if** condition is not satisfied, and **iniPos** or **finPos** // is “-1” we return “”, otherwise we return the received string. if( iniPos != -1 || finPos != - 1 ) return ""; return seq; } }

java string recursion methods parentheses
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.