这是我在 Google CodeJam 资格赛第二题中提交的代码,但编译器显示RunTime Error。但这在代码块上运行得很好。这是为什么?
问题
给定一串数字S,在其中插入最少数量的左括号和右括号,使得结果字符串是平衡的,并且每个数字d正好位于d对匹配括号内。让字符串中两个括号的嵌套成为严格出现在它们之间的子字符串。如果左括号和右括号的嵌套为空,或者嵌套中的每个括号都与嵌套中的另一个括号匹配,则称其匹配。位置p的嵌套深度是匹配括号m的对数,使得p包含在m的嵌套中。
例如,在以下字符串中,所有数字都与其嵌套深度匹配:
0((2)1)
,(((3))1(2))
,((((4))))
,((2))((2))(1)
. 前三个字符串在具有相同顺序的相同数字的字符串中长度最小,但最后一个没有,因为((22)1)
也有数字221
并且更短。
鉴于数字的字符串小号,找到另一个字符串S“包括括号和数字,例如:在所有的括号S”匹配其他一些括号,从消除任何和所有的括号S“的结果小号,在每个数字S”是等于它的嵌套深度,S'是最小长度。
#include <stdio.h>
#include <string.h>
int main() {
int t, k = 0;
scanf("%d", &t);
while (t--) {
int d, first, num = 0, brackets = 0;
char ch = '(', ch1 = ')';
char str1[100], str2[100] = {};
scanf("%s", &str1);
first = str1[0] - '0';
num = first;
brackets = first;
for (int i = 0; i < first; i++) {
strncat(str2, &ch, 1);
}
strncat(str2, &str1[0], 1);
for (int i = 1; i < strlen(str1); i++) {
d = str1[i] - '0';
if (d == num) {
strncat(str2, &str1[i], 1);
} else
if (d > num) {
int diff = d - num;
for (int j = 0; j < diff; j++) {
strncat(str2, &ch, 1);
brackets++;
}
strncat(str2, &str1[i], 1);
} else {
int diff = num - d;
for (int j = 0; j < diff; j++) {
strncat(str2, &ch1, 1);
brackets--;
}
strncat(str2, &str1[i], 1);
}
num = str1[i] - '0';
}
while (brackets > 0) {
strncat(str2, &ch1, 1);
brackets--;
}
k++;
printf("Case #%d: %s\n", k, str2);
}
return 0;
}
我检查了问题的描述,发现了这个:
Limits
Time limit: 20 seconds per test set.
Memory limit: 1GB.
1 ≤ T ≤ 100.
1 ≤ length of S ≤ 100.
所以输入字符串可以是 100 个字符。
你的代码是
char str1[100],str2[100]={};
所以你不能存储超过 99 个字符。
此外,输出字符串可能比输入字符串大得多。
例子:
Input: 909
Output (((((((((9)))))))))0(((((((((9)))))))))
所以你需要使输出字符串更大。我还没有计算出最大值,但如果你把它放大 20 倍,你就安全了。
char str1[101],str2[20 * 101]= { 0 };
^^^ ^^^^^^^^^ ^
但是为什么有一个输出字符串呢?只需打印出字符而不是将它们存储在字符串中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句