0
我希望我的程序一次讀取輸入的一行,並將每行寫入輸出,如果它不是前面一些輸入行的重複項。此外,具有大量重複行的文件不會使用比唯一行數所需的內存更多的內存。如何按特定順序長度順序列出字符串項目?
重複行應打印相同數量的時候,他們發生在輸入我也做了問題的一半但仍不能正常工作..
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將允許您跟蹤程序讀取的每個字符串,並檢查重複項。但是它並沒有給你一種'記住'你看過那個字符串的次數。另外,一個集合並不代表它存儲的元素的任何特定「順序」。 – user1445967
您可以將線條保留爲鍵和任何線條(頻率)的出現次數作爲該特定鍵的值。 –