【发布时间】:2013-09-23 02:57:27
【问题描述】:
我希望我的程序一次读取一行输入,如果每行与之前的某个输入行不重复,则将每一行写入输出。此外,具有大量重复行的文件使用的内存不会超过唯一行数所需的内存。
重复行的打印次数应与它们在输入中出现的次数相同 我已经完成了一半的问题,但仍然无法正常工作..
public class Part1 {
public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
Set<String> s = new HashSet<String>();
String inpt;
int n = 0;
while ((inpt = r.readLine()) != null) {
s.add(inpt);
n++;
}
Iterator<String> i = s.iterator();
while (i.hasNext()) {
w.println(i.next());
}
}
public static void main(String[] args) {
try {
BufferedReader r;
PrintWriter w;
if (args.length == 0) {
r = new BufferedReader(new InputStreamReader(System.in));
w = new PrintWriter(System.out);
} else if (args.length == 1) {
r = new BufferedReader(new FileReader(args[0]));
w = new PrintWriter(System.out);
} else {
r = new BufferedReader(new FileReader(args[0]));
w = new PrintWriter(new FileWriter(args[1]));
}
long start = System.nanoTime();
doIt(r, w);
w.flush();
long stop = System.nanoTime();
System.out.println("Execution time: " + 10e-9 * (stop-start));
} catch (IOException e) {
System.err.println(e);
System.exit(-1);
}
}
}
}
【问题讨论】:
-
你说“它不能正常工作”是什么意思。究竟出了什么问题?
-
解决问题最重要的步骤之一是确定如何表示您的程序需要跟踪的信息。具体来说,您要使用哪些数据结构(通常是对象)来执行此操作。您对 HashSet 的使用将允许您跟踪程序读取的每个字符串,并检查重复项。但是,它并不能让您“记住”您看过该字符串的次数。此外,集合并不代表它所存储元素的任何特定“顺序”。
-
您可以将您的行作为键,并将任何行的出现次数(频率)作为该特定键的值。
标签: java arraylist data-structures hashset