[LeetCode] Count the Number of Consistent Strings

아르당·2026년 6월 15일

LeetCode

목록 보기
357/561
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

서로 다른 문자로 구성된 문자열 allowed와 문자열 배열 words가 주어진다. 문자열은 문자열에서 모든 문자가 문자열 allowed에 나타난다면 일관된다고 한다.

배열 word에서 일관된 문자열의 수를 반환해라.

Example

#1
Input: allowed = "ab", words = ["ad", "bd", "aaab", "baa", "badab"]
Output: 2
Explanation: 문자열 "aaab"와 "baa"만 문자 'a'와 'b'를 포함한다.

#2
Input: allowed = "abc", words = ["a", "b", "c", "ab", "ac", "bc", "abc"]
Output: 7
Explanation: 모든 문자열이 일관된다.

#3
Input: allowed = "cad", words = ["cc", "acd", "b", "ba", "bac", "bad", "ac", "d"]
Output: 4
Explanation: 문자열 "cc", "acd", "ac", "d"는 일관된다.

Constraints

  • 1 <= words.length <= 10^4
  • 1 <= allowed.length <= 26
  • 1 <= words[i].length <= 10
  • allowed의 문자는 겹치지 않는다.
  • words[i]와 allowed는 오직 영어 소문자로만 구성된다.

Solved

class Solution {
    public int countConsistentStrings(String allowed, String[] words) {
        int n = words.length;
        int count = 0;

        for(String word: words){
            for(char c : word.toCharArray()){
                if(!allowed.contains(String.valueOf(c))){
                    count++;
                    break;
                }
            }
        }

        return n - count;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글