치악산 복숭아
[Leetcode] 383. Ransom Note - C++ 본문
두 개의 문자열 ransomNote과 magazine이 주어진다. magazine의 각 문자로 ransomNote의 문자열을 완성할 수 있다면 true를, 아니라면 false를 반환하는 문제이다.
- 접근 방법
- ransomNote의 각 문자가 magazine에 있는지 찾는다.
- 있다면 magazine에 있는 해당 문자를 제거한다.
- 없다면 바로 false 리턴
- 1번을 ransomeNote의 길이만큼 for문을 다 돌았다면 true를 리턴
- ransomNote의 각 문자가 magazine에 있는지 찾는다.
- 구현 코드
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
for(char c : ransomNote) {
int index = magazine.find(c);
if(index == -1) return false;
magazine.erase(index, 1);
}
return true;
}
};
나처럼 magazine의 원본 문자열을 지우는 방식이 아닌 map이나 hash 자료구조를 이용해서 각 문자의 빈도수를 카운트하는 방식도 많이 사용하는 것 같았다. 나도 다음에 써봐야징
'PS:0' 카테고리의 다른 글
[Leetcode] 1. Two Sum - C++ (2) | 2025.02.09 |
---|---|
[Leetcode] 66. Plus One - C++ (0) | 2025.02.08 |
[Leetcode] 20. Valid Parentheses - C++ (0) | 2025.02.02 |
[Leetcode] 278. First Bad Version - C++ (0) | 2025.02.01 |
[Leetcode] 409. Longest Palindrome - C++ (0) | 2025.01.31 |
Comments