Cho mảng chuỗi và một chuỗi tham chiếu định nghĩa thứ tự bảng chữ cái mới. Sắp xếp mảng chuỗi theo thứ tự đó. Ví dụ mảng ["hello", "programming", "science", "computer", "india"], chuỗi tham chiếu "pigvxbskyhqzelutoacfjrndmw" → kết quả ["programming", "india", "science", "hello", "computer"].
Cách làm: xây unordered_map ánh xạ ký tự → thứ tự trong chuỗi tham chiếu. So sánh chuỗi bằng cách tra map thay vì so sánh ASCII.
Ví dụ
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <vector>
using namespace std;
unordered_map<char, int> char_map;
bool compare(string c1, string c2) {
for (int i = 0; i < min(c1.size(), c2.size()); i++) {
if (char_map[c1[i]] == char_map[c2[i]])
continue;
return char_map[c1[i]] < char_map[c2[i]];
}
return c1.size() < c2.size();
}
int main() {
string str = "pigvxbskyhqzelutoacfjrndmw";
vector<string> v{ "hello", "programming", "science", "computer", "india" };
char_map.clear();
for (int i = 0; i < str.size(); i++)
char_map[str[i]] = i;
sort(v.begin(), v.end(), compare);
for (auto x : v)
cout << x << " ";
}
Kết quả
programming india science hello computer