알고리즘/LeetCode

[LeetCode/easy] Ransom Note

녕이 2022. 8. 12. 23:51
728x90

 

https://leetcode.com/problems/ransom-note/

 

Ransom Note - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

alpha 배열을 통해서 해당 알파벳 개수를 세고 magazine에서 해당 알파벳 개수를 감소시킨다.

만약 0보다 큰 게 있다면 ransomNote에 아직 알파벳이 남았는데 magazine이 끝난 것이므로 return false

 

bool canConstruct(string ransomNote, string magazine) {
    bool answer = true;
    int alpha[26];
    for(int i=0; i<26; i++) alpha[i] = 0;
    
    for(int i=0; i<ransomNote.size(); i++) alpha[ransomNote[i]-'a']++;
    for(int i=0; i<magazine.size(); i++) alpha[magazine[i]-'a']--;
    
    for(int i=0; i<26; i++) if(alpha[i] > 0) return false;
    return answer;
}

 

 

 

728x90