java - 试图找到一个返回两个括号之间的字符串的递归方法
问题描述
字符串中只有一对括号并且它们是平衡的,我不能使用内部用于循环的方法,例如包含等,并且禁止使用正则表达式。
这是我想出的代码,但它总是显示错误。
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));
}*/
解决方案
因此,例如,给定一个输入字符串:
Paren(thesis)String
你想打印:
thesis
让我们将此字符串视为字符数组并引入两个索引:first
和size
。
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);
}
推荐阅读
- django - 如何在 Django 中创建动态链接
- c - 在 C 中打印子字符串时出现虚假的换行符+空格
- amazon-web-services - 无法通过 SSH 连接到 AWS 实例 ubuntu 并且托管站点无法正常工作
- java - 如何在java中将表格从word文档复制到pdf文档?
- google-cloud-platform - GCP:如何将 Cloud Function 出口与 europe-north1 IP 地址相关联?
- javascript - 如何将 MongooseArray.prototype.pull() 与打字稿一起使用?
- express - Socket.io 房间没有收到消息
- javascript - 如何从 html 代码中隐藏/屏蔽 data-plyr-provider
- java - 是否可以将 spring data jpa 与 spring data jdbc 一起使用?
- node.js - 从 Firebase 存储下载