我正在尝试解决 UVa 问题号为 10324 的问题,我编写了以下解决方案,虽然通过了测试,但运行时间非常糟糕,需要 2.670 秒。 我有以下两个代码: 这是我的代码:
public static void main(String[] args) throws Exception{
// write your code here
StringBuilder op = new StringBuilder();
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(isr);
String input, tmp[];
int n, l, u, j, i = 0;
boolean dec;
char thi;
while ((input = reader.readLine()) != null) {
op.append("Case " + (++i) + ":\n");
n = Integer.parseInt(reader.readLine());
while (n-- > 0) {
tmp = reader.readLine().split(" ");
l = Integer.parseInt(tmp[0]);
u = Integer.parseInt(tmp[1]);
if (l > u) {
l ^= u;
u ^= l;
l ^= u;
}
//System.out.println(l + "|" + u);
dec = true;
thi = input.charAt(l++);
for (; l <= u; l++) {
if (thi != input.charAt(l)||(thi != input.charAt(u--))) {
dec = false;
break;
}
}
op.append((dec ? "Yes\n" : "No\n"));
}
}
System.out.print(op.toString());
return;
}
}
另外一段代码我在Mr Gorgon的解决方案中发现。这段代码的运行时间为0.84秒
public static void main(String[] args) throws Exception {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder("");
int testCase = 1;
String line;
while ((line = br.readLine()) != null) {
sb.append("Case ").append(testCase).append(":\n");
testCase++;
int noOfCases = Integer.parseInt(br.readLine());
for (int j = 0; j < noOfCases; j++) {
String[] str = br.readLine().split(" ");
int val1 = Integer.parseInt(str[0]);
int val2 = Integer.parseInt(str[1]);
if (val1 > val2) {
val1 ^= val2;
val2 ^= val1;
val1 ^= val2;
}
boolean isValid = true;
if (val1 != val2) {
for (int i = val1; i < val2; i++) {
if (line.charAt(i) != line.charAt(i + 1)) {
isValid = false;
break;
}
}
}
if (isValid)
sb.append("Yes\n");
else
sb.append("No\n");
}
}
System.out.print(sb);
}
我觉得很难理解为什么这段代码在所有任务本质相同的情况下运行得如此之快,而我的代码比Gorgon的代码声明更少。