【发布时间】:2021-11-28 03:22:22
【问题描述】:
我正在解决一个问题,给定一个字符串,括号中的子字符串后跟大括号中的值,字符串通过重复子字符串的次数来扩展。所以如果你有 (ab(d){3}){2} 你会得到 abdddabddd。
我觉得我在正确的轨道上,但 1. 这效率很低, 2. 测试似乎没有返回。希望得到一些帮助!
public class ExpandedString {
public static String expandedString(String inputStr) {
while (inputStr.contains("(")) {
for (int i = 0; i < inputStr.length(); i++) {
//check if there's something to repeat
if (inputStr.charAt(i) == '{') {
int temp = i;
//find what you need to repeat
while (inputStr.charAt(temp) != '(') {
temp--;
}
String inputStr2 = inputStr.substring(i);
int numTimes = i + inputStr.indexOf("}");
//replace (blah) with blah times repeated numTimes
StringBuilder repeated = new StringBuilder();
for(int j = 0; j<numTimes;j++) {
repeated.append(inputStr.substring(temp + 1, i - 1));
}
inputStr.replace(inputStr.substring(temp, i), repeated.toString());
//start again
i = 0;
}
}
}
return inputStr;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// input for inputStr
String inputStr = in .nextLine();
String result = expandedString(inputStr);
System.out.print(result);
}
}
【问题讨论】:
-
请添加失败的测试用例预期输出、实际输出和调试信息。