Leet Code 알고리즘
(Leet Code c++)Valid Anagram
naeunchan
2021. 7. 28. 10:03
728x90
반응형
242. Valid Anagram
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
Example 1:
Input: s = "anagram", t = "nagaram" Output: true
Example 2:
Input: s = "rat", t = "car" Output: false
Constraints:
- 1 <= s.length, t.length <= 5 * 104
- s and t consist of lowercase English letters.
주어진 두 문자열의 문자 수가 같은지 확인하면 되는 문제.
두 문자열의 길이가 같지 않으면 바로 false를 리턴.
s의 각 문자 개수를 알 수 있는 sMap과
t의 각 문자 개수를 알 수 있는 tMap이 있다.
길이가 같기 때문에 for문을 s 또는 t 문자열의 길이만큼 반복하여,
각 문자의 개수를 map에 저장한다.
그리고 다시 for문을 사용하여,
해당 문자의 개수가 같은지 확인하면 끝!
class Solution {
public:
bool isAnagram(string s, string t) {
map<char, int> sMap;
map<char, int> tMap;
if(s.size() != t.size()){
return false;
}
for(int i = 0; i < s.size(); i++){
sMap[s[i]]++;
tMap[t[i]]++;
}
for(int i = 0; i < s.size(); i++){
if(sMap[s[i]] != tMap[s[i]]){
return false;
}
}
return true;
}
};
728x90
반응형