본문 바로가기

공부, 알고리즘/LeetCode (리트코드)

[리트코드/JAVA] 1832. Check if the Sentence Is Pangram

leetcode.com/problems/check-if-the-sentence-is-pangram/

 

Check if the Sentence Is Pangram - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

# 문제설명

pangram is a sentence where every letter of the English alphabet appears at least once.

 

Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise.

 

Pangram이란 모든 알파벳이 적어도 한 번은 사용되는 문장입니다. 

주어진 문자열 sentence에 알파벳 소문자가 한 번씩 포함되어 있으면 true, 그렇지않으면 false를 반환하세요.

 

# 제한사항

  • 1 <= sentence.length <= 1000
  • sentence consists of lowercase English letters.

# 입출력 예

Example 1:

Input: sentence = "thequickbrownfoxjumpsoverthelazydog"

Output: true

Explanation: sentence contains at least one of every letter of the English alphabet.

 

Example 2:

Input: sentence = "leetcode"

Output: false

 

# 풀이

class Solution {
  public boolean checkIfPangram(String sentence) {
    boolean flag = false;
    ArrayList<Character> list = new ArrayList<>();

    if(sentence.length() < 26) return flag;
    else {

      for(int i=0; i<sentence.length(); i++) {

        if(!list.contains(sentence.charAt(i))) {
        	list.add(sentence.charAt(i));
        }
      }

      if(list.size() == 26) flag=true;

    }

    return flag;
  }
}

 

#3, 4

true, false 값을 반환할 flag변수와 중복제거를 위한 list를 선언합니다.

 

#6

먼저 입력받은 문자열 sentence의 길이가 26자 미만이면 바로 false를 리턴하고 종료합니다.

(Pangram은 모든 알파벳을 최소 한 번씩 사용해서 만든 문자열이기 때문입니다.)

 

#7 ~

26글자가 넘으면 중복제거 작업을 시작합니다.

 

#9 ~ 14

sentence길이만큼 반복할 for문을 선언합니다.

.contains()와 .charAt() 메소드를 사용해서 sentence를 한 글자씩 확인합니다.

list안에 중복되는 값이 없으면 해당 알파벳을 추가합니다.

 

#16 ~ 20

작업을 완료하면 list 크기가 26인지 확인합니다.

sentence의 알파벳을 중복제거 했을 때 크기가 26이면 모든 알파벳을 한 번씩 사용한 문자이기 때문입니다.

크기가 26이면 flag값을 true로 변경하고 반환합니다. 만약 크기가 26이 아니라면 false값을 그대로 반환합니다.