Detect Pangram in Java

The challenge

A pangram is a sentence that contains every single letter of the alphabet at least once. For example, the sentence “The quick brown fox jumps over the lazy dog” is a pangram, because it uses the letters A-Z at least once (case is irrelevant).

Given a string, detect whether or not it is a pangram. Return True if it is, False if not. Ignore numbers and punctuation.

The solution in Java code

Option 1 (using a Character loop):

public class PangramChecker {
    public boolean check(String sentence){
      for (char c = 'a'; c<='z'; c++)
        if (!sentence.toLowerCase().contains("" + c))
          return false;
      return true;
    }
}

Option 2 (using a functional programming to reduce and count the distinct characters):

class PangramChecker {
    boolean check(final String sentence) {
        return sentence.chars()
            .filter(Character::isLetter)
            .map(Character::toLowerCase)
            .distinct()
            .count() == 26;
    }
}

Option 3 (using an explicit check on all the characters):

public class PangramChecker {
  public boolean check(String sentence){
        String x = sentence.toLowerCase();
        if(x.contains("a") && x.contains("b") && x.contains("c") && x.contains("d")
                && x.contains("e") && x.contains("f") && x.contains("g")
                && x.contains("h") && x.contains("i") && x.contains("j")
                && x.contains("k") && x.contains("l") && x.contains("m")
                && x.contains("n") && x.contains("o") && x.contains("p")
                && x.contains("q") && x.contains("r") && x.contains("s")
                && x.contains("t") && x.contains("u") && x.contains("v")
                && x.contains("w") && x.contains("x") && x.contains("y")
                && x.contains("z")){
            return true;
        }else{
            return false;
        }
    }
}

Test cases to validate our solution

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;


public class PangramTest {
    @Test
    public void test1() {
      String pangram1 = "The quick brown fox jumps over the lazy dog.";
      PangramChecker pc = new PangramChecker();
      assertEquals(true, pc.check(pangram1));
    }
    @Test
    public void test2() {
      String pangram2 = "You shall not pass!";
      PangramChecker pc = new PangramChecker();
      assertEquals(false, pc.check(pangram2));
    }
}
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments