반응형
포인트
1. 연관되어 있는 단어, 포함되어 있는 단어를 찾는 문제, 적절히 set과 map 을 사용하여 해결하자
🧶문서는 항상 수정 될 수 있습니다. 비판은 환영합니다.
c++/cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int countConsistentStrings(string allowed, vector<string> &words)
{
int count = 0;
for(auto ele1: words){
unordered_set<char> set(ele1.begin(), ele1.end());
for(auto ele2 : set){
if(allowed.find(ele2)==string::npos){
count+=1;
break;
}
}
}
return words.size() - count;
}
int countConsistentStrings2(string allowed, vector<string>& words) {
// support variable
int res = words.size();
unordered_set<char> set;
// populating alpha
for (char c: allowed) set.insert(c);
// parsing all the words to see if each character is in alpha
for (string word: words) {
// in case we find an unallowed character, we decrease res and break
for (char c: word) if (set.find(c)==set.end()) {
res--;
break;
}
}
return res;
}
};
python
class Solution:
def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
count = 0
for ele1 in words:
temp_set = set(ele1)
for ele2 in temp_set:
if allowed.find(ele2) == -1:
count+=1
break
return len(words) - count
def countConsistentStrings2(self, allowed: str, words: List[str]) -> int:
return sum(not set(w) - set(allowed) for w in words)
def countConsistentStrings3(self, allowed: str, words: List[str]) -> int:
res = len(words)
m_set = set(allowed)
for ele1 in words:
for ele2 in ele1:
if ele2 not in m_set:
res-=1
break
return res
반응형
'알고리즘' 카테고리의 다른 글
[알고리즘] Count Primes (0) | 2021.02.04 |
---|---|
[알고리즘] Goal Parser Interpretation (0) | 2021.02.01 |
[알고리즘] Check If Two String Arrays are Equivalent (0) | 2021.01.31 |
[알고리즘] 짝지어 제거하기 (0) | 2021.01.28 |
[알고리즘 ] Concatenation of Consecutive Binary Numbers (0) | 2021.01.28 |
댓글