LeetCode 面試題 17.07嬰兒名字 (並查集+字符串處理+字典序)

嬰兒名字

1600ms,吐了 ,代碼看似很長。但主要花在了字符串處理上。

string s;
s.substring(int idx,int len);  //去除子串
stoi(string s);   //將s的值換算10進制整數
s.find(string target); //得到目標字符串的匹配的位置。
struct Node{
    int ID;
    string name;
    int num;
    Node(string name,int num):name(name),num(num){}
    Node(int ID,string name,int num=0):ID(ID),name(name),num(num){}
};

struct MFS{
    int f[100000+10];
    MFS(int n){
        for(int i=1;i<=n+1;i++){
            f[i] = i;
        }
    }
    int find(int x){
        return x==f[x]?x:f[x]=find(f[x]);
    }
    
    void merge(int x,int y){
        f[find(x)] = find(y);
    }
};

class Solution {
public:
    vector<Node> namesVector;
    map<string,int> mp;
    map<int,Node> answer;
    vector<string> result;
    
    MFS mfs;
    
    vector<string> trulyMostPopular(vector<string>& names, vector<string>& synonyms){
        int ID = 1 ;
        for(auto s:names){
            int id1 = (int)s.find("(");
            int id2 = (int)s.find(")");
            string name = s.substr(0,id1);
            int num = stoi(s.substr(id1+1,id2-id1-1));
            mp[name] = ID;
            namesVector.push_back(Node(ID,name,num));
            ID++;
        }

        for(auto s:synonyms){
            int id = (int)s.find(",");
            string s1 = s.substr(1,id-1);
            string s2 = s.substr(id+1,s.length()-2-id);
            if(!mp.count(s1)){
                mp[s1] = ID;
                namesVector.push_back(Node(ID,s1));
                ID++;
            }
            if(!mp.count(s2)){
                mp[s2] = ID;
                namesVector.push_back(Node(ID,s2));
                ID++;
            }
            mfs.merge(mp[s1],mp[s2]);
        }
        for(auto node:namesVector){
            int fatherID = mfs.find(node.ID);
            if(!answer.count(fatherID)){
                answer[fatherID] = Node(node.ID,node.name,node.num);
            }else{
                string oldName = answer[fatherID].name;
                string newName = node.name;
                if(newName<oldName){
                    answer[fatherID].name = newName;
                }
                answer[fatherID].num+=node.num;
            }
        }
        
        map<int,Node>::iterator it = answer.begin();
        for(;it!=answer.end();it++){
            string s = (it->second).name+"("+ to_string((it->second).num) +")";
        }
        return result;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章