Problem
You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels.
Letters are case sensitive, so "a" is considered a different type of stone from "A".
Example 1:
Input: jewels = "aA", stones = "aAAbbbb" Output: 3
Example 2:
Input: jewels = "z", stones = "ZZ" Output: 0
Constraints:
- 1 <= jewels.length, stones.length <= 50
- jewels and stones consist of only English letters.
- All the characters of jewels are unique.
Solution(Python3)
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: count = 0 for i in range(len(stones)): for j in range(len(jewels)): if jewels[j] == stones[i]: count += 1 return count |
이 문제는 혼자서 거의 풀었지만 마지막에서 막혔다. 이 전에 이중 for문을 이해해서 금방 풀릴 줄 알았지만 그렇지 않았다... 문제는 jewels 소문자 a와 대문자 A가 stones의 배열에 있는지 없는지 확인하는 것이다.
설루션을 보면 if jewels[j] == stones [i]:이다. 처음에 [i], [j]의 존재를 확인하지 못했다.
그렇다면 작동은 어떻게 하느냐...

jewels [0] = a번째가 stones[0]와 동일한가
jewels [0] = a 번째가 stones[1]와 동일한가
jewels [0] = a 번째가 stones[2]와 동일한가
jewels [0] = a 번째가 stones[3]와 동일한가
jewels [0] = a 번째가 stones[4]와 동일한가
jewels [0] = a 번째가 stones[5]와 동일한가
jewels [0] = a 번째가 stones[6]와 동일한가
이 중에 a가 하나 있다. 그러서 count += 1에 추가한다.
jewels [1] = A번째가 stones[0]와 동일한가
jewels [1] = A 번째가 stones[1]와 동일한가
jewels [1] = A 번째가 stones[2]와 동일한가
jewels [1] = A 번째가 stones[3]와 동일한가
jewels [1] = A 번째가 stones[4]와 동일한가
jewels [1] = A 번째가 stones[5]와 동일한가
jewels [1] = A 번째가 stones[6]와 동일한가
이 중에 A가 두 개 있다. 그래서 count += 1 추가한다.
따라서 Output의 결과는 3이다.

'초보코딩' 카테고리의 다른 글
Leetcode - 1342. Number of Steps to Reduce a Number to Zero (0) | 2021.08.20 |
---|---|
Leetcode - 1365. How Many Numbers Are Smaller Than the Current Number (0) | 2021.08.18 |
LeetCode - 1431. Kids With the Greatest Number of Candies (0) | 2021.08.09 |
LeetCode - 1470. Shuffle the Array (0) | 2021.08.08 |
LeetCode - 1672. Richest Customer Wealth (0) | 2021.08.06 |