我想知道是否有人能指引我走向正確的方向。打印出列表中最長的迴文
我有一個超過40萬字的外部文本文件,其目的是打印出每個詞是迴文,這是我做的,但現在我正試圖弄清楚如何收集10個最長的迴文所有印製在打印機上的副本,並將頂部10分開,並將它們打印到控制檯上。
如果有人能讓我開始,我畫空白!
這裏是我的代碼:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
// store external text file into a new File object
File file = new File("dict.txt");
try {
// new Scanner object to read external file
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
// read each word so long as there is a word on subsequent line
String word = sc.nextLine();
// if the word is a palindrome
if (isPalindrome(word)) {
// print out the palindrome word to console
System.out.println(word + " is a palindrome");
}
}
} catch(FileNotFoundException fnfe) {
// if file is not found, print error to console
System.out.println(fnfe.toString());
}
} // end main
public static boolean isPalindrome(String word) {
// if there is no word
if (word == null || word.length() == 0) {
// return false
return false;
}
// StringBuilder to hold a variable of the reverse of each word
String reverse = new StringBuilder(word).reverse().toString();
// if the reversed word equals the original word
if (reverse.equals(word)) {
// it is a palindrome
return true;
}
// return false if no palindrome found
return false;
} // end isPalindrome
} // end class Palindrome
提前任何建議謝謝!
這需要'O(number-of-unique-words)'空間 – tucuxi
@tucuxi:是的,沒有空間或時間要求。有很多優化可能,可以存儲前10個迴文的最小大小,甚至不會去驗證單詞<=是否是迴文。 – gfelisberto
通常,在空間和時間上編寫更高效的代碼被認爲是更好的。因此,雖然你的答案在技術上有效,但我覺得它可以得到改善。因此,評論。 – tucuxi