Programers:さっきの歌


さっきの歌は



コード#コード#

#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

bool compare(pair<string,int> a, pair<string,int> b){
    if(a.second == b.second) return false; // false이면 교환하지 X
    return a.second > b.second;
}
string solution(string m, vector<string> musicinfos) {
    string answer = "";
    /* m을 vector로 만들기 */
    vector<string> mv;
    for(int j = 0;j<m.length();j++) {
        if(m[j] == '#')
            mv[mv.size()-1] += "#";
        else{
            string t = "";
            t += m[j];
            mv.push_back(t);                
        }
    }
    if(musicinfos.empty()) return "(None)";
    /* 음악 이름 / 재생된 시간 */
    vector<pair<string, int>> v;
    int i=0;    
    while(i < musicinfos.size())
    {
        int H = stoi(musicinfos[i].substr(6,2)) - stoi(musicinfos[i].substr(0,2));
        int M = stoi(musicinfos[i].substr(9,2)) - stoi(musicinfos[i].substr(3,2));
        int total = H*60 + M;
        vector<string> origin;
        string name = "";
        /* name 구하기 */
        int z =12;
        for(;z<musicinfos[i].length();z++){
            if(musicinfos[i][z] == ',') break;
            name += musicinfos[i][z];
        }
        /* original 음표 구하기 */
        for(z += 1;z<musicinfos[i].length();z++) {
            if(musicinfos[i][z] == '#')
                origin[origin.size()-1] += "#";
            else{
                string t = "";
                t += musicinfos[i][z];
                origin.push_back(t);                
            }
        }
        vector<string> str;
        /* 총 음표 문자열 구하기 */
        for(int j=0;j<total;j++) 
            str.push_back(origin[j%origin.size()]);
        for(int j=0;j<str.size();j++)
        {
            if(str[j] != mv[0]) continue;
            int flag = 0;
            for(int k=0;k<mv.size();k++)
            { 
                if(str[j+k] != mv[k]) {
                    flag = 1;
                    break;
                }
            }
            if(flag == 0) 
            {
                v.push_back({name, total});
                break;
            }
        }
        i++;
    }
    if(v.empty()) answer = "(None)";
    else {
        sort(v.begin(), v.end(), compare);
        answer = v.front().first;
    }
    return answer;
}
  • key point!
    1)#乃至vector<string>を記憶し、#文字を処理する
    -->C#cと同様に、他の文字の代わりに比較するのも一つの方法です!
    2)sortで用いるcompare()定義の場合、return falseであればX
  • を交換する.