250x250
반응형
Notice
Recent Posts
Recent Comments
Link
N
(Leet Code c++)Ransom Note 본문
728x90
반응형
383. Ransom Note
Given two stings 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.
주어진 문자열 magazine의 각 단어를 순회하면서 나온 알파벳의 횟수를 알 수 있도록 카운팅한다.
이후 ransomNote도 순회하면서 check 벡터에 있는 알파벳 횟수를 줄여준다.
만약 해당 알파벳의 값이 0 이하라면 바로 false를 반환.
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
vector<int> check(26, 0);
for(int i = 0; i < magazine.size(); i++){
check[magazine[i] - 'a']++;
}
for(int i = 0; i < ransomNote.size(); i++){
if(check[ransomNote[i] - 'a']-- <= 0){
return false;
}
}
return true;
}
};
728x90
반응형
'Leet Code 알고리즘' 카테고리의 다른 글
(Leet Code c++)FIrst Unique Character in a string (0) | 2021.08.16 |
---|---|
(Leet Code c++)3Sum (0) | 2021.08.10 |
(Leet Code c++)Cuess Number Higher or Lower (0) | 2021.08.09 |
(Leet Code c++)Valid Perfect Square (0) | 2021.08.04 |
(Leet Code c++)Intersection of Two Arrays2 (0) | 2021.08.04 |