1. 程式人生 > >Leetcode953. Verifying an Alien Dictionary驗證外星語詞典

Leetcode953. Verifying an Alien Dictionary驗證外星語詞典

某種外星語也使用英文小寫字母,但可能順序 order 不同。字母表的順序(order)是一些小寫字母的排列。

給定一組用外星語書寫的單詞 words,以及其字母表的順序 order,只有當給定的單詞在這種外星語中按字典序排列時,返回 true;否則,返回 false。

 

示例 1:

輸入:words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz" 輸出:true 解釋:在該語言的字母表中,'h' 位於 'l' 之前,所以單詞序列是按字典序排列的。

示例 2:

輸入:words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz" 輸出:false 解釋:在該語言的字母表中,'d' 位於 'l' 之後,那麼 words[0] > words[1],因此單詞序列不是按字典序排列的。

示例 3:

輸入:words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz" 輸出:false 解釋:當前三個字元 "app" 匹配時,第二個字串相對短一些,然後根據詞典編纂規則 "apple" > "app",因為 'l' > '∅',其中 '∅' 是空白字元,定義為比任何其他字元都小(

更多資訊)。

 

提示:

  1. 1 <= words.length <= 100
  2. 1 <= words[i].length <= 20
  3. order.length == 26
  4. 在 words[i] 和 order 中的所有字元都是英文小寫字母。

 

 

 map<char, int> dict;

 bool cmp(string x, string y)
 {
	 int i =0,  j = 0;
	 int len1 = x.size();
	 int len2 = y.size();
	 while (i < len1 && j < len2)
	 {
		 if (x[i] == y[j])
		 {
			 i++;
			 j++;
		 }
		 else if (dict[x[i]] > dict[y[i]])
		 {
			 return false;
		 }
		 else
		 {
			 return true;
		 }
	 }
	 return i == j ? true : i > j ? false : true;
 }

 class Solution {
 public:
	 bool isAlienSorted(vector<string>& words, string order) 
	 {
		 for (int i = 0; i < 26; i++)
		 {
			 dict[order[i]] = i;
		 }
		 vector<string> newAry = words;
		 sort(newAry.begin(), newAry.end(), cmp);
		 for (int i = 0; i < words.size(); i++)
		 {
			 if (newAry[i] != words[i])
				 return false;
		 }
		 return true;
	 }
 };