문제 가 그 답지 어렵지 않다, 주어지는 두 개의 문자 중 하나의 문자를 이용해 다른 문자를 만들 수 있는지 물어보는 부분이다. 이것 역시 알파벳 소문자만 주어지기 때문에 배열로 바로 코드 치러가자.
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] alphabets = new int[26];
for(char c : magazine.toCharArray()){
alphabets[c-'a']++;
}
for(char c: ransomNote.toCharArray()){
alphabets[c-'a']--;
}
for(int x:alphabets){
if(x<0)return false;
}
return true;
}
}
만들 문자들을 하나씩 쪼개 배열에 넣어 카운트를 해주고, 문자를 만들 때 하나씩 뺀 후 만약 0보다 작다면? 바로 리턴해주면 된다.
'PS > LeetcCode' 카테고리의 다른 글
33. Search in Rotated Sorted Array (0) | 2022.07.04 |
---|---|
34. Find First and Last Position of Element in Sorted Array (0) | 2022.07.03 |
53. Maximum Subarray (0) | 2022.06.29 |
242. Valid Anagram (0) | 2022.06.26 |
387. First Unique Character in a String (0) | 2022.06.26 |