Created
September 6, 2014 21:27
-
-
Save sachin-handiekar/0cf8636014ee2e093a2a to your computer and use it in GitHub Desktop.
Palindrome
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.io.BufferedReader; | |
import java.io.FileInputStream; | |
import java.io.InputStream; | |
import java.io.InputStreamReader; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class WordUtils { | |
public static void main(String[] args) throws Exception { | |
String filename = "C:/txtfiles/Palindrome.txt"; | |
InputStream fis = new FileInputStream(filename); | |
BufferedReader br = new BufferedReader(new InputStreamReader(fis)); | |
String word = null; | |
int counter = 0; | |
List<String> palindromicWords = new ArrayList<String>(); | |
List<String> nonPalindromicWords = new ArrayList<String>(); | |
while ((word = br.readLine()) != null) { | |
if (isPalindrome(word)) { | |
palindromicWords.add(word); | |
counter++; | |
} else { | |
nonPalindromicWords.add(word); | |
} | |
} | |
System.out.println("Non palindromic words :: " + nonPalindromicWords); | |
System.out.println("Total Palindrome Words :: " + counter); | |
} | |
public static boolean isPalindrome(String word) { | |
if (word == null) { | |
throw new IllegalArgumentException("Word cannot be null."); | |
} | |
if (word.trim().length() == 0) { | |
throw new IllegalArgumentException("Word cannot be empty."); | |
} | |
boolean status = false; | |
char[] wordCharArray = word.toLowerCase().toCharArray(); | |
int len = wordCharArray.length; | |
for (int i = 0, j = len - 1; i < len - 1; i++, j--) { | |
if (wordCharArray[i] == wordCharArray[j]) { | |
status = true; | |
} else { | |
status = false; | |
break; | |
} | |
} | |
return status; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment