zoukankan      html  css  js  c++  java
  • 953.Verifying an Alien Dictionary(Map)

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

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

    使用Map将字典序映射为数字,进行比较

    class Solution {
        public boolean compare(Map<Character,Integer> ch,String string1,String string2){
            int len1 = string1.length();
            int len2 = string2.length();
            int len = len1 < len2 ?len1:len2;
            for(int i =0;i<len;i++){
                if(ch.get(string1.charAt(i)) < ch.get(string2.charAt(i)))  return true;
                else if(ch.get(string1.charAt(i)) == ch.get(string2.charAt(i)))
                    continue;
                else
                    return false;
            }
            if(len1<=len2)   return true;
            else    return false;
        }
        public boolean isAlienSorted(String[] words, String order) {
            Map<Character,Integer> ch = new HashMap<Character,Integer>();
            for(int i =0;i<order.length();i++){
                ch.put(order.charAt(i),i);
            }
            for(int i=1;i<words.length;i++){
                if(!compare(ch,words[i-1],words[i])) return false;
            }
            return true;
        }
    }
    
  • 相关阅读:
    2021寒假每日一题《棋盘挑战》
    2021寒假每日一题《货币系统》
    2021寒假每日一题《红与黑》
    2021寒假每日一题《字母图形》
    2021寒假每日一题《完全背包问题》
    2021寒假每日一题《找硬币》
    python 迭代器和生成器
    python for循环
    python集合
    python字符串常用操作
  • 原文地址:https://www.cnblogs.com/a1225234/p/10284599.html
Copyright © 2011-2022 走看看