LeetCode Alien Dictionary

时间:2022-05-15 17:30:24

原题链接在这里:https://leetcode.com/problems/alien-dictionary/

题目:

There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of non-empty words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.

Example 1:
Given the following words in dictionary,

[
"wrt",
"wrf",
"er",
"ett",
"rftt"
]

The correct order is: "wertf".

Example 2:
Given the following words in dictionary,

[
"z",
"x"
]

The correct order is: "zx".

Example 3:
Given the following words in dictionary,

[
"z",
"x",
"z"

The order is invalid, so return "".

Note:

  1. You may assume all letters are in lowercase.
  2. You may assume that if a is a prefix of b, then a must appear before b in the given dictionary.
  3. If the order is invalid, return an empty string.
  4. There may be multiple valid order of letters, return any one of them is fine.

题解:

采用BFS based topological sort. 建立graph 和 indegree array.

字典里有多个单词,这些竖着的单词是按照首字母排序的,如果首字母相同就看第二个字母,以此类推.

用queue把indegree为0的vertex加到queue中开始做BFS.

Note: when using while loop, first thing is to remember to increase index.

Time Complexity: O(V + E). Space: O(V). V最大26. Edge最大为words.length.

AC Java:

 class Solution {
public String alienOrder(String[] words) {
if(words == null || words.length == 0){
return "";
} //看看words array中都含有哪些字母
HashSet<Character> charSet = new HashSet<>();
for(String w : words){
for(char c : w.toCharArray()){
charSet.add(c);
}
} //构建 adjancy list 形式的graph, 计算每个vertex 的indegree
int [] in = new int[26];
HashMap<Character, HashSet<Character>> graph = new HashMap<>();
for(int i = 1; i < words.length; i++){
String pre = words[i - 1];
String cur = words[i];
int j = 0;
while(j < pre.length() && j < cur.length()){
if(pre.charAt(j) != cur.charAt(j)){
char sour = pre.charAt(j);
char dest = cur.charAt(j); graph.putIfAbsent(sour, new HashSet<Character>());
if(!graph.get(sour).contains(dest)){
in[dest - 'a']++;
} graph.get(sour).add(dest);
break;
} j++;
if(j < pre.length() && j == cur.length()){
return "";
}
}
} //BFS 形式的topologial sort
StringBuilder sb = new StringBuilder();
LinkedList<Character> que = new LinkedList<>();
for(char c = 'a'; c <= 'z'; c++){
if(in[c - 'a'] == 0 && charSet.contains(c)){
que.add(c);
}
} while(!que.isEmpty()){
char cur = que.poll();
sb.append(cur);
if(graph.containsKey(cur)){
for(char c : graph.get(cur)){
in[c - 'a']--;
if(in[c - 'a'] == 0){
que.add(c);
}
}
}
} //若是sb的length不等于uniqueChar的size, 说明剩下的部分有环
return sb.length() == charSet.size() ? sb.toString() : "";
}
}

类似Course Schedule.