269. 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.

一刷
题解:这题是根据具体的单词找出字典序。
方法:先建立相邻点的map>, 和出入度map, 为1度的点在前,移除,2度的点变为1度
由于不仅从左到右满足alphabetic, 从上到下也满足。
所以,上下相邻的两个word, 找到第一个不相同的首字母,那么一定是上面指向下面。(都只找第一个,因为后面的顺序不确定)
上下相邻的两个字母,找到第一个不一样的首字母a, b,那么图中一定是a->b. 如果采用word中相邻字母的顺序,很容易形成环。构造了graph和degree之后再采用BFS

public String alienOrder(String[] words) {
    Map> map=new HashMap>();
    Map degree=new HashMap();
    String result="";
    if(words==null || words.length==0) return result;
    for(String s: words){
        for(char c: s.toCharArray()){
            degree.put(c,0);
        }
    }
    for(int i=0; i set=new HashSet();
                if(map.containsKey(c1)) set=map.get(c1);
                if(!set.contains(c2)){
                    set.add(c2);
                    map.put(c1, set);
                    degree.put(c2, degree.get(c2)+1);
                }
                break;
            }
        }
    }
    Queue q=new LinkedList();
    for(char c: degree.keySet()){
        if(degree.get(c)==0) q.add(c);
    }
    while(!q.isEmpty()){
        char c=q.remove();
        result+=c;
        if(map.containsKey(c)){
            for(char c2: map.get(c)){
                degree.put(c2,degree.get(c2)-1);
                if(degree.get(c2)==0) q.add(c2);
            }
        }
    }
    if(result.length()!=degree.size()) return "";
    return result;
}

你可能感兴趣的:(269. Alien Dictionary)