`

Given a sorted dictionary of an alien language, find order of characters

阅读更多

Given a sorted dictionary (array of words) of an alien language, find order of characters in the language.

 

Examples:

Input:  words[] = {"baa", "abcd", "abca", "cab", "cad"}
Output: Order of characters is 'b', 'd', 'a', 'c'
Note that words are sorted and in the given language "baa" 
comes before "abcd", therefore 'b' is before 'a' in output.
Similarly we can find other orders.

Input:  words[] = {"caa", "aaa", "aab"}
Output: Order of characters is 'c', 'a', 'b'

The idea is to create a graph of characters and then find topological sorting of the created graph. Following are the detailed steps.

1) Create a graph g with number of vertices equal to the size of alphabet in the given alien language. For example, if the alphabet size is 5, then there can be 5 characters in words. Initially there are no edges in graph.

2) Do following for every pair of adjacent words in given sorted array.
…..a) Let the current pair of words be word1 and word2. One by one compare characters of both words and find the first mismatching characters.
…..b) Create an edge in g from mismatching character of word1 to that of word2.

3) Print topological sorting of the above created graph.

 

// A C++ program to order of characters in an alien language
#include<iostream>
#include <list>
#include <stack>
#include <cstring>
using namespace std;
 
// Class to represent a graph
class Graph
{
    int V;    // No. of vertices'
 
    // Pointer to an array containing adjacency listsList
    list<int> *adj;
 
    // A function used by topologicalSort
    void topologicalSortUtil(int v, bool visited[], stack<int> &Stack);
public:
    Graph(int V);   // Constructor
 
    // function to add an edge to graph
    void addEdge(int v, int w);
 
    // prints a Topological Sort of the complete graph
    void topologicalSort();
};
 
Graph::Graph(int V)
{
    this->V = V;
    adj = new list<int>[V];
}
 
void Graph::addEdge(int v, int w)
{
    adj[v].push_back(w); // Add w to v’s list.
}
 
// A recursive function used by topologicalSort
void Graph::topologicalSortUtil(int v, bool visited[], stack<int> &Stack)
{
    // Mark the current node as visited.
    visited[v] = true;
 
    // Recur for all the vertices adjacent to this vertex
    list<int>::iterator i;
    for (i = adj[v].begin(); i != adj[v].end(); ++i)
        if (!visited[*i])
            topologicalSortUtil(*i, visited, Stack);
 
    // Push current vertex to stack which stores result
    Stack.push(v);
}
 
// The function to do Topological Sort. It uses recursive topologicalSortUtil()
void Graph::topologicalSort()
{
    stack<int> Stack;
 
    // Mark all the vertices as not visited
    bool *visited = new bool[V];
    for (int i = 0; i < V; i++)
        visited[i] = false;
 
    // Call the recursive helper function to store Topological Sort
    // starting from all vertices one by one
    for (int i = 0; i < V; i++)
        if (visited[i] == false)
            topologicalSortUtil(i, visited, Stack);
 
    // Print contents of stack
    while (Stack.empty() == false)
    {
        cout << (char) ('a' + Stack.top()) << " ";
        Stack.pop();
    }
}
 
int min(int x, int y)
{
    return (x < y)? x : y;
}
 
// This function fidns and prints order of characer from a sorted
// array of words. n is size of words[].  alpha is set of possible
// alphabets.
// For simplicity, this function is written in a way that only
// first 'alpha' characters can be there in words array.  For
// example if alpha is 7, then words[] should have only 'a', 'b',
// 'c' 'd', 'e', 'f', 'g'
void printOrder(string words[], int n, int alpha)
{
    // Create a graph with 'aplha' edges
    Graph g(alpha);
 
    // Process all adjacent pairs of words and create a graph
    for (int i = 0; i < n-1; i++)
    {
        // Take the current two words and find the first mismatching
        // character
        string word1 = words[i], word2 = words[i+1];
        for (int j = 0; j < min(word1.length(), word2.length()); j++)
        {
            // If we find a mismatching character, then add an edge
            // from character of word1 to that of word2
            if (word1[j] != word2[j])
            {
                g.addEdge(word1[j]-'a', word2[j]-'a');
                break;
            }
        }
    }
 
    // Print topological sort of the above created graph
    g.topologicalSort();
}
 
// Driver program to test above functions
int main()
{
    string words[] = {"caa", "aaa", "aab"};
    printOrder(words, 3, 3);
    return 0;
}

 Time Complexity: The first step to create a graph takes O(n + alhpa) time where n is number of given words and alpha is number of characters in given alphabet. The second step is also topological sorting. Note that there would be alpha vertices and at-most (n-1) edges in the graph. The time complexity of topological sorting is O(V+E) which is O(n + aplha) here. So overall time complexity is O(n + aplha) + O(n + aplha) which is O(n + aplha).

来自:http://www.geeksforgeeks.org/given-sorted-dictionary-find-precedence-characters/

分享到:
评论

相关推荐

    Here are a few algorithmic problems for you to try: Problem 1:

    Given a sorted array of integers, write a function to find the first duplicate in the array. Example: input = [1, 2, 3, 4, 5, 2, 3] -&gt; output = 2 Problem 3: Given a binary tree, write a function to...

    Dictionary, SortedDictionary, SortedList 横向评测

    "Dictionary, SortedDictionary, SortedList 横向评测" Dictionary, SortedDictionary, SortedList 是 .NET Framework 中三个支持泛型和关键字查找的类,它们都属于 System.Collections.Generic 命名空间。这些类在...

    lrucacheleetcode-Algorithms:所有常用算法的集合

    https://www.geeksforgeeks.org/given-sorted-dictionary-find-precedence-characters/ 强连接组件 (SCC) BFS/DFS 的应用 - 2, 3, Bipartite check and 2 coloring problem 有向和无向图中的循环检测 联合查找 - ...

    LeetCode4 Median of Two Sorted Arrays

    There are two sorted arrays nums1 and nums2 of size m and n respectively. ...Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). Java AC版本

    折半查找 binarySearch

    If the list of names is in sorted order, a binary search will find a given name with far fewer probes than the simple procedure of probing each name in the list, one after the other in a linear ...

    Word Amalgamation

    The object of this game is to solve a riddle, but in order to find the letters that appear in the answer it is necessary to unscramble four words. Your task is to write a program that can unscramble ...

    34.Find First and Last Position of Element in Sorted Array在排序数组中寻找元素的第一和最后一个位置【LeetCode单题讲解系列】

    34.Find_First_and_Last_Position_of_Element_in_Sorted_Array在排序数组中

    Python Cookbook, 2nd Edition

    Processing All of a List's Items in Random Order Recipe 5.7. Keeping a Sequence Ordered as Items Are Added Recipe 5.8. Getting the First Few Smallest Items of a Sequence Recipe 5.9. Looking for...

    前端开源库-sorted-indexof

    `sorted-indexof` 的核心功能在于它提供的方法能够快速地找到一个已排序数组 `a` 中,来自另一个已排序数组 `b` 的元素的对应索引。这与 JavaScript 内置的 `indexOf` 方法不同,后者在未排序的数组中寻找元素时会...

    算法上机!!

    Give a divide and conquer algorithm for the following problem: you are given two sorted lists of size m and n, and are allowed unit time access to the ith element of each list. Give an O(lg m + lgn) ...

    ssd5 ex4 给需要帮助的人。这是ssd5 ex4

    This method returns a copy of the invoking Listing object sorted by the field name given in the parameter. Use an appropriate STL sorting function to sort the advertisements. To sort based on the ...

    2009 达内Unix学习笔记

    [] 匹配中括号里的内容[a-z][A-Z][0-9]。 ! 事件。 $ 取环境变量的值。 | 管道。把前一命令的输出作为后一命令的输入,把几个命令连接起来。 |经常跟tee连用,tee 把内容保存到文档并显示出来。 三、通用后...

    Lerner -- Python Workout. 50 Essential Exercises -- 2020.pdf

    - **Objective:** Sort the characters of a given string alphabetically. - **Key Concepts:** - Converting strings to lists. - Using the `sorted()` function. - Joining sorted characters back into a ...

    Find the specified number of characters_查找指定字符个数_TheNumber_

    sorted_count = sorted(char_count.items(), key=lambda x: x[1], reverse=True) return sorted_count ``` 现在,我们不仅可以获取单个字符的计数,还可以得到一个列表,其中包含所有字符及其按降序排列的出现...

    微软内部资料-SQL性能优化5

    If there is no clustered index, there is a sysindexes row for the table with an indid value of 0, and that row will keep track of the address of the first IAM for the table. The IAM is a giant bitmap...

    实现Dictionary正反向排序

    综上所述,实现`Dictionary`的正反向排序,可以借助`SortedList`、`OrderedDictionary`、`List`结合自定义比较器,或者利用`LINQ`查询。选择哪种方法取决于具体的需求,如性能、内存占用以及是否需要改变原始数据...

    Algorithms in C++, Parts 1-4: Fundamentals, Data Structures, Sorting, Searching

    6. **Strings**: Strings are sequences of characters and are a common type of data. This chapter covers string manipulation techniques and data structures optimized for handling strings. 7. **Compound...

    median-of-two-sorted-arrays

    Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). Example 1: nums1 = [1, 3] nums2 = [2] The median is 2.0 Example 2: nums1 = [1, 2] nums2 = [3, 4...

    i-vector的工具箱

    or against the background model and a given speaker model to accept/reject an identity claim (speaker verification). On the other hand, in the i-vector framework the speaker models are estimated ...

    leetcode苹果-verifying-an-alien-dictionary:验证外星人词典

    sorted. Example 2: Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz" Output: false Explanation: As 'd' comes after 'l' in this language, then words[0] &gt; words[1], hence t

Global site tag (gtag.js) - Google Analytics