Java实现嵌套标记字符串展开功能代码运行异常求助
代码问题分析
- String为不可变类型,
inputStr.replace()执行后不会修改原字符串,你没有将返回值重新赋值给inputStr,导致while循环的判断条件inputStr.contains("(")永远为真,程序陷入死循环,这是无返回结果的核心原因 - 重复次数计算逻辑错误:
inputStr.indexOf("}")是从字符串起始位置查找第一个}的下标,而非当前{对应的闭合},且你直接将下标相加作为重复次数,没有提取{}中间的数字做数值转换,重复次数完全不正确 - 替换范围计算错误:你只替换了左括号到{的部分,没有包含对应的},导致括号残留,循环永远无法退出
- 每次替换后直接将i重置为0从头遍历,会产生大量重复遍历操作,运行效率低下
修正后可运行代码
import java.util.Scanner; import java.util.Stack; public class ExpandedString { public static String expandedString(String inputStr) { Stack<StringBuilder> strStack = new Stack<>(); Stack<Integer> numStack = new Stack<>(); StringBuilder currentStr = new StringBuilder(); int num = 0; for (char c : inputStr.toCharArray()) { if (Character.isDigit(c)) { // 拼接多位数的重复次数 num = num * 10 + (c - '0'); } else if (c == '(') { // 左括号入栈,保存当前状态 strStack.push(currentStr); numStack.push(num); currentStr = new StringBuilder(); num = 0; } else if (c == ')') { // 右括号出栈,拼接重复内容 int repeatTimes = numStack.pop(); StringBuilder temp = strStack.pop(); for (int i = 0; i < repeatTimes; i++) { temp.append(currentStr); } currentStr = temp; } else if (c != '{' && c != '}') { // 普通字符直接拼接 currentStr.append(c); } } return currentStr.toString(); } public static void main(String[] args) { Scanner in = new Scanner(System.in); String inputStr = in.nextLine(); String result = expandedString(inputStr); System.out.print(result); } }
优化说明
- 采用栈结构处理嵌套括号场景,单次遍历即可完成展开,时间复杂度为O(n)(n为最终展开后的字符串长度),运行效率远高于原来的多层循环反复遍历方案
- 支持多位数的重复次数,比如(abc){10}可以正确展开10次
- 无需反复修改字符串,避免了大量字符串复制和重复遍历操作
内容的提问来源于stack exchange,提问作者anon comp
相关产品推荐
相关产品推荐

