leetcode講解--953. Verifying an Alien Dictionary

題目

In an alien language, surprisingly they also use english lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters.java

Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographicaly in this alien language.數組

Example 1:app

Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
Output: true
Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted.

Example 2:less

Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"
Output: false
Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.

Example 3:this

Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"
Output: false
Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info).

Note:code

  1. 1 <= words.length <= 100
  2. 1 <= words[i].length <= 20
  3. order.length == 26
  4. All characters in words[i] and order are english lowercase letters.

題目地址遞歸

講解

這道題講道理,我以爲有點難。可能遞歸的解法比較簡單吧。剛開始我思路一直是錯的,正確的思路應該是先深刻比較兩個字符串,沒有問題再比較下一對字符串(這是一種深度優先,我剛開始一直是廣度優先的思路)。主要的麻煩來自於對數組越界的判斷。three

java代碼

class Solution {
    public boolean isAlienSorted(String[] words, String order) {
        if(words.length==1){
            return true;
        }
        Map<Character, Integer> map = new HashMap<>();
        for(int i=0;i<order.length();i++){
            map.put(order.charAt(i), i);
        }
        for(int i=1;i<words.length;i++){
            int index = 0;
            boolean indexOut = false;
            if(index>words[i-1].length()-1){
                continue;
            }
            if(index>words[i].length()-1){
                return false;
            }
            while(map.get(words[i].charAt(index))==map.get(words[i-1].charAt(index))){
                index++;
                System.out.println(index);
                if(index>words[i-1].length()-1){
                    indexOut=true;
                    break;
                }
                if(index>words[i].length()-1){
                    return false;
                }
            }
            if(indexOut){
                continue;
            }
            if(map.get(words[i].charAt(index))<map.get(words[i-1].charAt(index))){
                return false;
            }
        }
        return true;
    }
}
相關文章
相關標籤/搜索