1. 程式人生 > >791. Custom Sort String的C++解法

791. Custom Sort String的C++解法

先根據S給一個比較大小的字典,然後再把T排序。

 class Solution {
 public:
	 string customSortString(string S, string T) {
		 string res = "";
		 map<char,int> index;
		 for (int i = 0; i < S.length(); i++) index[S[i]] = i;
		 for (int i = 0; i < T.length(); i++)
		 {
			 if (!index.count(T[i])) res = res + T[i];
			 else {
				 int j = 0;
				 while ((index[T[i]] > index[res[j]])&&(j<res.length())) j++;
				 res.insert(j, T.substr(i,1));
			 }
		 }
		 return res;
	 }
 };

另一種寫法,自定義sort:

class Solution {
  public:
    string customSortString(string S, string T) {
        sort(T.begin(), T.end(),
             [&](char a, char b) { return S.find(a) < S.find(b); });
        return T;
    }
};

還有一種寫法是傳一個函式名,參考這裡

以上兩種方法都不是最快的,最快的方法是統計T中每個字母出現的次數然後直接根據字典新增對應次數的字母:

class Solution {
public:
    string customSortString(string S, string T) {
        unordered_map<char, int> counts;
        for(auto ch : T)
            counts[ch]++;
        
        vector<char> sol;
        for(auto ch : S)
            while(counts[ch]--)
                sol.push_back(ch);
        
        for(auto ch : T) 
            if( counts[ch] > 0 )
                sol.push_back(ch);
        
        return string(sol.begin(), sol.end());
    }
};