Go語言leetcode題解953驗證外星語詞典示例詳解
題目描述
某種外星語也使用英文小寫字母,但可能順序 order 不同。字母表的順序(order)是一些小寫字母的排列。
給定一組用外星語書寫的單詞 words,以及其字母表的順序 order,只有當(dāng)給定的單詞在這種外星語中按字典序排列時,返回 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 解釋:當(dāng)前三個字符 "app" 匹配時,第二個字符串相對短一些,然后根據(jù)詞典編纂規(guī)則 "apple" > "app",因為 'l' > '?',其中 '?' 是空白字符,定義為比任何其他字符都?。ǜ嘈畔ⅲ?
提示:
1 <= words.length <= 100
1 <= words[i].length <= 20
order.length == 26
在 words[i] 和 order 中的所有字符都是英文小寫字母。
思路分析
- 哈希表存儲字母和對應(yīng)的索引,判斷字符串先后關(guān)系的時候要用到
- 然后比較兩個字符串,選較短的長度來比較
- a[i]對應(yīng)的字典中的索引為indexA;
- b[i]對應(yīng)的字典中的索引為indexB;
- 如果indexA < indexB, 直接返回true;
- 如果indexA > indexB, 直接返回false;
- 如果前minLen個字符都相等的話,最后判斷下字符串的長度
AC 代碼
class Solution {
public:
bool compare(string& a, string& b, unordered_map<char, int>& mp) {
int sizeA = a.size();
int sizeB = b.size();
int minLen = sizeA > sizeB ? sizeB : sizeA;
int same = 0;
for (int i = 0; i < minLen; i++) {
if (mp[a[i]] < mp[b[i]]) {
return true;
} else if(mp[a[i]] > mp[b[i]]) {
return false;
}else if (mp[a[i]] == mp[b[i]]) {
same++;
}
}
if (same == minLen) {
return a.size() < b.size();
}
return false;
}
bool isAlienSorted(vector<string>& words, string order) {
unordered_map<char, int> mp;
for (int i = 0; i < 26; i++) {
mp[order[i]] = i;
}
int size = words.size();
if (size == 1) {
return true;
}
for (int i = 0; i < (size - 1); i++) {
if (compare(words[i], words[i+1], mp) == false) {
return false;
}
}
return true;
}
};以上就是Go語言leetcode題解953驗證外星語詞典示例詳解的詳細(xì)內(nèi)容,更多關(guān)于Go 驗證外星語詞典的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Linux系統(tǒng)下Go語言開發(fā)環(huán)境搭建
這篇文章主要介紹了Linux系統(tǒng)下Go開發(fā)環(huán)境搭建,需要的朋友可以參考下2022-04-04

