【发布时间】:2015-06-07 15:56:01
【问题描述】:
我一直在解决一个问题,
它只是从控制台逐行读取并找到该部分 其中包含一个模式并将其替换为实际数字
资源:spoj
首先我尝试使用查找文本的模式并将其替换为实际数字,方法是根据需要添加或减去
我的代码
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class ABSYS {
public static void main(String[] args) throws IOException {
int t;
String[] numArray = new String[2];
String[] numArray2 = new String[2];
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
t = Integer.parseInt(reader.readLine());
while(t > 0) {
String input = reader.readLine();
if(input.isEmpty()) {
continue;
}
numArray = input.split("\\s{1}=\\s{1}");
numArray2 = numArray[0].split("\\s{1}\\+\\s{1}");
Pattern pattern = Pattern.compile("machula");
Matcher matcher = pattern.matcher(numArray[1]);
if(matcher.find()) {
System.out.println(numArray[0] + " = " + (Integer.parseInt(numArray2[0]) + Integer.parseInt(numArray2[1])));
}
else {
matcher = pattern.matcher(numArray2[0]);
if(matcher.find()) {
System.out.println((Integer.parseInt(numArray[1]) - Integer.parseInt(numArray2[1])) + " + " + numArray2[1] + " = " + numArray[1]);
}
else {
System.out.println(numArray2[0] + " + " + (Integer.parseInt(numArray[1]) - Integer.parseInt(numArray2[0])) + " = " + numArray[1]);
}
}
t--;
}
}
}
我在 ideone 用 120 个测试用例实现它后得到了这个
成功时间:0.14 内存:320832 信号:0
之后,为了测试,我完全改变了,去掉了模式和匹配器,改用了try catch
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
class ABSYS {
public static void main(String[] args) throws IOException {
int t;
String[] numArray = new String[2];
String[] numArray2 = new String[2];
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
t = Integer.parseInt(reader.readLine());
while(t > 0) {
String input = reader.readLine();
if(input.isEmpty()) {
continue;
}
numArray = input.split("\\s{1}=\\s{1}");
numArray2 = numArray[0].split("\\s{1}\\+\\s{1}");
int a = 0, b = 0, c = 0;
try {
c = Integer.parseInt(numArray[1]);
try {
a = Integer.parseInt(numArray2[0]);
System.out.println(a+" + "+(c - a)+" = "+c);
}
catch(NumberFormatException nfe) {
b = Integer.parseInt(numArray2[1]);
System.out.println((c - b)+" + "+b+" = "+c);
}
}
catch(NumberFormatException nfe) {
System.out.println(numArray[0] + " = " + (Integer.parseInt(numArray2[0]) + Integer.parseInt(numArray2[1])));
}
t--;
}
}
}
我用相同的输入得到这个结果
成功时间:0.15 内存:320832 信号:0
我想不通,为什么即使在删除 find 方法作业之后,下一个实现的时间也会增加。
是不是因为try-catch,如果是,为什么会这样?
【问题讨论】:
-
This post 可能会很有帮助。
-
我不认为 try catch 块对此负责。
-
我假设时间以秒为单位。那么这个差异只有1/100秒。这不是什么值得担心的事情。这很可能是记录开始和停止时间的人为因素。
-
您无法以这种方式衡量 Java 程序的性能...您的结果取决于很多因素,以至于您无法从中得出任何结论...
标签: java