Created
June 4, 2013 23:27
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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