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:
Input:
[
“wrt”,
“wrf”,
“er”,
“ett”,
“rftt”
]
Output: “wertf”
Example 2:
Input:
[
“z”,
“x”
]
Output: “zx”
Example 3:
Input:
[
“z”,
“x”,
“z”
]
Output: “”
Explanation: The order is invalid, so return “”.
Note:
You may assume all letters are in lowercase.
You may assume that if a is a prefix of b, then a must appear before b in the given dictionary.
If the order is invalid, return an empty string.
There may be multiple valid order of letters, return any one of them is fine.
做这题前得先熟悉拓扑排序的套路:
晨哥Leetcode 207. Course Schedule 拓扑排序套路
比较容易错、不好处理的有几个点:
- 所有在字符串里出现过的,都得出现在结果里,所以要用一个set存一下
- 没有出现在字符串里的,不要输出 (外星人里可能没有这个字符)
- 多个字符串排序比较 (我的解法是用递归,不过更好的办法是用下面这个办法)
while (index < words[i].length() && index < words[i + 1].length()) {
if (words[i].charAt(index) != words[i + 1].charAt(index)) {
graph.get(words[i].charAt(index)).add(words[i + 1].charAt(index));
break;
}
index++;
}
此题代码量大,还是挺容易出错的,需要多练习
class Solution {
public String alienOrder(String[] words) {
int[] degree = new int[26];
List[] edges = new ArrayList[26];// 依赖i的有哪些
for(int i = 0; i< 26; i++) {
edges[i] = new ArrayList();
}
Set<Integer> set = new HashSet();
for(String s : words) {
for(char c : s.toCharArray()) {
set.add(c - 'a');
}
}
getOrder(Arrays.asList(words), degree, edges);
Queue<Integer> q = new LinkedList();
for(int i = 0; i< 26; i++) {
if(set.contains(i) && degree[i] == 0) {
q.offer(i);
}
}
StringBuilder sb = new StringBuilder();
while(!q.isEmpty()) {
Integer cur = q.poll();
sb.append((char)(cur+'a'));
for(Object o: edges[cur]) {
Integer next = (Integer)o;
if(--degree[next] == 0) {
q.offer(next);
}
}
}
return sb.length() == set.size() ? sb.toString() : "";
}
private void getOrder(List<String> words, int[] degree, List[] edges) {
Character prev = null;
List<String> curList = new ArrayList();
for(String word : words) {
if(word.length() == 0) continue;
Character cur = word.charAt(0);
if(prev != null && !prev.equals(cur)) {
degree[cur - 'a']++;
edges[prev - 'a'].add(cur-'a');
if(curList.size() > 1) {
getOrder(curList, degree, edges);
}
curList = new ArrayList();
}
prev = cur;
if(word.length() > 1)
curList.add(word.substring(1));
}
if(curList.size() > 1) {
getOrder(curList, degree, edges);
}
}
}