我用Java实现了一个程序,令人惊讶的是,特殊测试用例需要177M内存(我没有因为程序被一个网站测试过)。
问题是找出串S1中存在的字符串S2的所有字符。并且有N个这样的情况。
public static void main(String[] args) throws Exception {
BufferedReader bin = new BufferedReader (new InputStreamReader (System.in));
String jewel, stone;
int t = Integer.parseInt (bin.readLine());
int count;
int i;
while (t-->0) {
count = 0;
jewel = bin.readLine();
stone = bin.readLine();
for (i=0; i
if (jewel.indexOf(stone.charAt(i)) !=-1) {
count++;
}
}
System.out.println(count);
}
}我也不明白,它是如何取177M的公羊。即使他们正在测试一个巨大的文件,那么也只有2个字符串在那里。但是,代码完美地工作并通过了测试用例。
由于Java程序占用了大量的内存,所以我计划编写一个C程序。具体如下:
int main ()
{
char * pch;
char jewel[100], stone[100];
int n;
scanf("%d",&n);
int len;
int tp;
int count = 0;
getchar(); // remove trailing '\n'
while (n-->0) {
gets(jewel);
pch = gets(stone);
count = 0;
while(*pch ) {
if (strchr(jewel, *pch)) {
count++;
}
pch++;
}
printf("%d\n", count);
}
return 0;
}在现有案例很少的情况下,它正在工作。程序似乎也是正确的。但我无法理解为什么它正确地传递所有测试用例。
所有字符串缓冲区都足够长,以容纳传入的字符串,这些字符串由新行分隔。
编辑:更改""+stone.charAt(i))到stone.charAt(i))没有帮助,并采取相同数量的内存。另外为什么这个C代码不能通过所有的测试用例?