홍시홍의 프로그래밍

[2020 카카오 공채] 가사 검색 본문

알고리즘 문제풀이/카카오

[2020 카카오 공채] 가사 검색

홍시홍 2020. 8. 8. 16:11

분류 

시뮬레이션

 

요구사항

가사에 사용된 모든 단어들이 담긴 배열 words와 찾고자 하는 키워드가 담긴 배열 queries가 주어질 때, 각 키워드 별로 매치된 단어가 몇 개인지 순서대로 배열에 담아 반환하도록 solution 함수를 완성

 

풀이

fro?? 라면 앞의 3단어만 fro라면 모든 단어가 해당 단어로 count 된다

??fro 라면 뒤의 3단어만 fro라면 모든 단어가 해당 단어로 count 된다

 

그러므로 길이와 앞 혹은 뒤 단어만 비교하면 된다

앞 혹은 뒤의 index를 반환하는 함수를 만들어 주어진 배열과 길이와 해당 index의 문자를 비교해본다

 

bool com(string a, string b){
    if(a.size() < b.size()) return true;
    return false;
}
int Getfindstart(string str){
    int flag=0;
    for(int i =0 ; i <str.size() ; i++){
        char now_ch = str[i];
        if(now_ch!='?') return i;
    }
}
int Getfindend(string str){
    int flag=0;
    for(int i =str.size()-1 ; i >=0 ; i--){
        char now_ch = str[i];
        if(now_ch !='?') return i;
    }
}
vector<int> solution(vector<string> words, vector<string> queries) {
    vector<int> answer;
    sort(words.begin(),words.end(),com);
    vector<string> my_words[10100];
    for(auto i : words){
        my_words[i.size()].push_back(i);
    }
    for(int i=0 ; i <queries.size() ; i++){
        string now_str= queries[i];
        int start_pos = Getfindstart(queries[i]);
        int end_pos = Getfindend(queries[i]);
        string temp_str= now_str.substr(start_pos,end_pos-start_pos+1);
        int now_size= now_str.size();
        int cnt=0;

        for(int j=0 ; j <my_words[now_size].size() ; j++){
            if(temp_str==my_words[now_size][j].substr(start_pos,end_pos-start_pos+1)){
                cnt++;
            }
        }
        answer.push_back(cnt);
    }
    return answer;
}
Comments