Problem solving/Algorithms

[LeetCode] 1684. Count the Number of Consistent Strings (Python)

Young_A 2021. 1. 10. 09:57

LeetCode - Problems - Algorithms - 1684. Count the Number of Consistent Strings

Problem Description

You are given a string allowed consisting of distinct characters and an array of strings words.

A string is consistent if all characters in the string appear in the string allowed.

Return the number of consistent strings in the array words.

 

Example:

Constraints:

My Solution (Python)

class Solution(object):
    def countConsistentStrings(self, allowed, words):
        """
        :type allowed: str
        :type words: List[str]
        :rtype: int
        """
        answer = len(words)

        for word in words:
            for l in word:
                if l not in allowed:
                    answer -= 1
                    break
                    
        return answer

์ฃผ์–ด์ง„ ๋‹จ์–ด๋“ค์ด ํ—ˆ์šฉ๋œ ์•ŒํŒŒ๋ฒณ๋งŒ์œผ๋กœ ์ด๋ฃจ์–ด์ ธ์žˆ๋Š” ๋‹จ์–ด๋ฅผ ์ฐพ๊ณ , ์กฐ๊ฑด์„ ์ถฉ์กฑํ•˜๋Š” ๋‹จ์–ด์˜ ๊ฐฏ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•ด์•ผํ•œ๋‹ค.

์šฐ์„ ์€ ์ •๋‹ต์œผ๋กœ ์ œ์ถœํ•  answer๋ฅผ words์˜ ๊ธธ์ด๋กœ ์„ ์–ธํ•ด์ค€๋‹ค.

words ๋ฆฌ์ŠคํŠธ์˜ ๋‹จ์–ด๋ฅผ ์ฐจ๋ก€๋Œ€๋กœ ํ™•์ธํ•˜๊ณ , ๊ทธ ์•ˆ์˜ letter๋“ค๊นŒ์ง€ ํ™•์ธํ•˜๋Š” ๋‘ ๊ฐœ์˜ for๋ฌธ์„ ์ด์šฉํ•œ๋‹ค.

๋งŒ์•ฝ์— ํ™•์ธํ•˜๋˜ letter๊ฐ€ allowed์— ์—†๋‹ค๋ฉด, answer๋ฅผ 1 ๊ฐ์†Œ ์‹œํ‚ค๊ณ  ๋‚ด๋ถ€ for๋ฌธ์„ ์ข…๋ฃŒํ•˜๊ณ  ์™ธ๋ถ€ for๋ฌธ์˜ ๋‹ค์Œ ๋ฐ˜๋ณต์„ ์ˆ˜ํ–‰ํ•œ๋‹ค.

 

์ „์ฒด ๋‹จ์–ด์˜ ๊ฐฏ์ˆ˜์—์„œ ์กฐ๊ฑด์„ ์ถฉ์กฑํ•˜์ง€ ์•Š๋Š” ๋‹จ์–ด๊ฐ€ ๋ฐœ๊ฒฌ๋ ๋•Œ๋งˆ๋‹ค 1์”ฉ ๊ฐ์†Œ์‹œํ‚ค๋Š” ๋ฐฉ๋ฒ•์„ ์„ ํƒํ•œ ์ด์œ ๋Š”, ํ•œ ๋ฒˆ ํ—ˆ์šฉ๋˜์ง€ ์•Š์€ letter๊ฐ€ ๋ฐœ๊ฒฌ๋˜๋ฉด ๋‚˜๋จธ์ง€ letter๋“ค์„ ํ™•์ธํ•  ํ•„์š”๊ฐ€ ์—†๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

0์—์„œ ๋‹จ์–ด์˜ ๋ชจ๋“  letter๊ฐ€ allowed์— ํฌํ•จ๋˜๋Š”์ง€ ํ™•์ธํ•œ ๋’ค์— 1 ์”ฉ ์ฆ๊ฐ€์‹œํ‚ค๋Š” ๋ฐฉ๋ฒ•๋ณด๋‹ค ๋” ์ ์€ ํšŸ์ˆ˜์˜ ๋ฐ˜๋ณต์„ ์‹คํ–‰ํ•˜๋ฏ€๋กœ ํšจ๊ณผ์ ์ด๋‹ค.