https://leetcode.com/problems/shortest-completing-word/description/
Shortest Completing Word - LeetCode
Can you solve this real interview question? Shortest Completing Word - Given a string licensePlate and an array of strings words, find the shortest completing word in words. A completing word is a word that contains all the letters in licensePlate. Ignore
leetcode.com
구현 문제였습니다.
📕 풀이방법
📔 풀이과정
1. licensePlate를 순회하며 걸러진 소문자 알파벳의 빈도수를 저장할 vector <int> charMap을 선언해 저장합니다.2. word의 최대 길이는 15이므로 정답을 비교할 result를 선언해 최대길이 16으로 초기화해줍니다.3. words의 원소를 순회하며 하나의 word에 알파벳의 빈도수를 wMap을 선언해 저장해줍니다.4. 26개의 알파뱃에 대해 순회하며 wMap[i] < charMap[i]이라면 complete된 단어가 아니므로 걸러줍니다.5. complete단어면서 더 짧은 단어가 있다면 result에 word를 저장해줍니다.
📔 정답 출력 | 반환
result를 반환합니다.
📕 Code
📔 C++
class Solution {
public:
static bool cmp (string a, string b) {
return a.size() < b.size();
}
string shortestCompletingWord(string licensePlate, vector<string>& words) {
vector <int> charMap(26,0);
for(auto l : licensePlate) {
if(isalpha(l))
charMap[tolower(l) - 'a']++;
}
string result = string(16, 'z');
for(string &w : words) {
vector <int> wMap(26,0);
for(auto c : w) wMap[c-'a']++;
bool isComplete = true;
for(int i = 0; i < 26; i++) {
if(wMap[i] < charMap[i]) {
isComplete = false;
break;
}
}
if(isComplete && w.size() < result.size()) result = w;
}
return result;
}
};
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Implementation' 카테고리의 다른 글
(C++) - LeetCode (easy) 766. Toeplitz Matrix (0) | 2023.07.11 |
---|---|
(C++) - LeetCode (easy) 762. Prime Number of Set Bits in Binary Representation (0) | 2023.07.10 |
(C++) - LeetCode (easy) 747. Largest Number At Least Twice of Others (0) | 2023.07.04 |
(C++) - LeetCode (easy) 728. Self Dividing Numbers.cpp (0) | 2023.06.26 |
(C++) - LeetCode (easy) 709. To Lower Case (0) | 2023.06.21 |