Adriana was playing with the English alphabet. When she was done playing with the alphabet, she realized that she had jumbled up the positions of the letters. Now, given a set of words, she wondered what would be the dictionary ordering of these words based on the new alphabet ordering which she made.
In other words, given a permutation of the English alphabet, E, and a set of words S, you need to output the lexicographical ordering of the words in the set S based on the new alphabet, E.
Example:
Input: s = "abcdefghijklmnopqrstuvwxyz", m = 2, v = {"aa", "bb"}
Output:
aa bb
Approach:
C++
#include <bits/stdc++.h>using namespace std;unordered_map<char, int> ump;bool cmp(string a, string b){for (int i = 0; i < min(a.size(), b.size()); i++){if (ump[a[i]] == ump[b[i]])continue;return ump[a[i]] < ump[b[i]];}return a.size() < b.size();}void missingAlphabets(string s, vector<string> &v, int m){ump.clear();for (int i = 0; i < s.size(); i++)ump[s[i]] = i;sort(v.begin(), v.end(), cmp);for (int i = 0; i < m; i++)cout << v[i] << "\n";}int main(){string s = "abcdefghijklmnopqrstuvwxyz";int m = 2;vector<string> v = {"aa", "bb"};missingAlphabets(s, v, m);return 0;}
No comments:
Post a Comment