外星人图像和外星人太空船
Problem Statement:
问题陈述:
Given a sorted dictionary (array of words) of an alien language, find order of characters in the language.
给定外语的排序字典(单词数组),找到该语言中字符的顺序。
Example:
例:
List of words: {'aba', 'ddc', 'cab', 'ebd', 'cc' }
Output: order of the characters is :abde c
List of words: {'abb', 'caa', 'dda', 'bba' }
Output: order of the characters is :acdb
Algorithm:
算法:
To solve this problem we follow this approach:
为了解决这个问题,我们采用以下方法:
First, we take two strings and compare each element of the same level of two string (like "aba", "ddc").
首先,我们采用两个字符串,并比较两个字符串的相同级别的每个元素(例如“ aba” , “ ddc” )。
After making the comparison we make an edge between them (a → d, b → d, a → c).
在进行比较之后,我们在它们之间建立了一条优势(a→d,b→d,a→c) 。
After comparing all the strings we draw the graph between the letters.
比较所有字符串之后,我们在字母之间绘制图形。
After getting the graph we topologically sort that graph. (to know about the topological sort).
得到图后,我们对该图进行拓扑排序。 (了解拓扑排序 )。
外来字典的C ++实现 (C++ Implementation for alien dictionary)
#include <bits/stdc++.h>
using namespace std;
void addedge(list<int>* ls, int x, int y)
{
ls[x].push_back(y);
}
string topological_sort(list<int>* ls, int k)
{
char arr[k];
stack<int> s;
set<int> st;
int ind = k - 1;
for (int i = k - 1; i >= 0; i--) {
if (st.find(i) == st.end()) {
s.push(i);
st.insert(i);
//check all the non visited nodes
while (!s.empty()) {
int p = s.top();
list<int>::iterator it;
int temp = 0;
//check its adjacent non visited nodes
for (it = ls[p].begin(); it != ls[p].end(); it++) {
if (st.find(*it) == st.end()) {
st.insert(*it);
s.push(*it);
temp = 1;
}
}
//if all adjaceny nodes are visited
//then pop that element from stack
if (temp == 0) {
char ch = (char)(p + 'a');
arr[ind] = ch;
ind--;
s.pop();
}
}
}
}
return arr;
}
string printOrder(string dict[], int k)
{
list<int> ls[k];
for (int i = 0; i < k - 1; i++) {
string word1 = dict[i];
string word2 = dict[i + 1];
//comparing the two strings
for (int j = 0; j < min(word1.length(), word2.length()); j++) {
if (word1[j] != word2[j]) {
//make an egde between them
addedge(ls, word1[j] - 'a', word2[j] - 'a');
break;
}
}
}
return topological_sort(ls, k);
}
int main()
{
string dict[4] = { "abb", "caa", "dda", "ba" };
cout << printOrder(dict, 4);
return 0;
}
Output
输出量
acdb
外星人图像和外星人太空船