Byte by Byte

1002. Find Common Characters.cpp 본문

개발 로그/알고리즘

1002. Find Common Characters.cpp

CyberSoak 2021. 11. 19. 21:19

🔑 

1. 이전 워드에서 각 알파벳 카운트 저장(check[26])

2. 다음 워드에서 각 알파벳 카운트 저장(tmp[26])

3. tmp[26]에 0인 것 -> check[26] 도 0 대입.

4. 만약 둘다 양수 일 경우, 적은 것을 check[26]에 대입.

5. 워드 끝까지 반복.

6. check[26]에 저장된 수 만큼 character를 string으로 변환하여 res vector에 삽입.

class Solution {
public:
    vector<string> commonChars(vector<string>& words) {
        vector<string>res;
        int check[26] = {0,};
        
        for(int j =0; j<words[0].size(); j++){
                check[words[0][j]-'a']++;
        }
        
        for(int i =1; i<words.size(); i++){
            int tmp[26]={0,};
            for(int j =0; j<words[i].size(); j++){
                tmp[words[i][j]-'a']++;
            }
            for(int k = 0; k<26; k++){
                if(tmp[k]==0){
                   check[k]=0;
                }
                else{
                    check[k] = min(check[k],tmp[k]);
                }
            }
        }
        
        for(int k =0; k<26; k++){
            for(int i =0; i<check[k]; i++){
                string x = "";
                x += char('a'+k);
                res.push_back(x);
            }
        }
        
        return res;
    }
};