Pangrams Implementation in Java
The sentence "The quick brown fox jumps over the lazy dog" contains every single letter in the alphabet. Such sentences are called pangrams.
import java.util.Scanner;
import java.util.TreeSet;
/**
*
*
* @author xyz
*
*/
public class PangramDetector {
/**
* Main method to execute the Pangram detector
*
* @param args
*/
public static void main(String[] args) {
PangramDetector pangramDetector = new PangramDetector();
String line = null;
try{
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter a sentence: ");
line = userInput.nextLine();
String missingLetters = pangramDetector.findMissingLetters(line);
System.out.println("Output: \"" + missingLetters + "\"");
} catch (Exception e) {
System.out.println("Something is wrong: "+e.getMessage());
}
}
/**
* Find the missing letters from the user input. Time complexity for this
* method may go up to nlogn. I am ingnoring 26 alphabet letter as small number may not help to find complexity
*
* @param sentence
* @return
*/
public String findMissingLetters(String sentence) {
final char[] alphabetArray = "abcdefghijklmnopqrstuvwxyz".toCharArray();
final TreeSet alphabetTreeSet = new TreeSet();
// Convert sentence to char array.
final char[] sentenceChar = sentence.toLowerCase().toCharArray();
// Keep a set of those chars that are present in sentence.
for (final char letter : sentenceChar) {
alphabetTreeSet.add(letter);
}
// Print the chars present in the alphabet but not in the user input.
final StringBuilder missingCharBuilder = new StringBuilder();
for (final char character : alphabetArray) {
if (!alphabetTreeSet.contains(character)) {
missingCharBuilder.append(character);
}
}
return missingCharBuilder.toString();
}
Output:
Output:
A) "The quick brown fox jumps over the lazy dog"
Returns: ""
(This sentence contains every letter)
B) "The slow purple oryx meanders past the quiescent canine"
Returns: "bfgjkvz"
C) "We hates Bagginses!"
Returns: "cdfjklmopqruvxyz"
No comments:
Post a Comment
Please advise or upload your post here