Description
주어진 magazine 배열이 ransomNote에 주어진 단어를 포함할 수 있는지 여부를 반환하는 문제입니다.
Given two strings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise.
Each letter in magazine can only be used once in ransomNote.
Example 1:
Input: ransomNote = "a", magazine = "b"
Output: false
Example 2:
Input: ransomNote = "aa", magazine = "ab"
Output: false
Example 3:
Input: ransomNote = "aa", magazine = "aab"
Output: true
Constraints:
- 1 <= ransomNote.length, magazine.length <= 105
- ransomNote and magazine consist of lowercase English letters.
Solution 1. Hash Table
public boolean canConstruct(String ransomNote, String magazine) {
int[] map = new int[26];
for (int i = 0; i < magazine.length(); i++) {
map[magazine.charAt(i)-'a']++;
}
for (int i = 0; i < ransomNote.length(); i++) {
if(--map[ransomNote.charAt(i)-'a'] < 0){
return false;
}
}
return true;
}
소문자는 26자리기 때문에 각 문자를 인덱스로 가지는 배열을 맵으로 사용하여 문자별 카운트를 기록해 두고 ransomNote의 단어를 만들 수 없는 경우 (배열의 요소값이 음수 전환) false 반환하고 모든 문자열 검색을 다 통과했을 경우 true를 반환해 줍니다.
Reference
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 941. Valid Mountain Array - 문제풀이 (0) | 2022.01.25 |
---|---|
[LeetCode] 520. Detect Capital - 문제풀이 (0) | 2022.01.25 |
[LeetCode] 387. First Unique Character in a String - 문제풀이 (0) | 2022.01.23 |
[LeetCode] 134. Gas Station - 문제풀이 (0) | 2022.01.23 |
[LeetCode] 2148. Count Elements With Strictly Smaller and Greater Elements - 문제풀이 (0) | 2022.01.23 |