Skip to content

Instantly share code, notes, and snippets.

@vaskoz
Created June 4, 2013 23:27
Show Gist options
  • Save vaskoz/5710492 to your computer and use it in GitHub Desktop.
Save vaskoz/5710492 to your computer and use it in GitHub Desktop.
Print out the palindromes for a list of new line separated words read in from standard input. Usage: java Palindromes < /usr/share/dict/words
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Palindromes {
public static void main(String[] args) {
Set<String> words = new HashSet<String>();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String word = scanner.next().toLowerCase();
if (word.length() == 1) continue;
words.add(word);
}
for (final String s : words) {
StringBuilder sb = new StringBuilder(s.length());
char[] letters = s.toCharArray();
for (int i = letters.length-1; i >= 0; i--) {
sb.append(letters[i]);
}
final String reversed = sb.toString();
if (s.equals(reversed))
System.out.println(s);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment