Leetcode PHP題解--D61 953. Verifying an Alien Dictionary

D61 953. Verifying an Alien Dictionary

題目連接

953. Verifying an Alien Dictionaryphp

題目分析

給定一個單詞數組和一個字符串,判斷給定的數組是否知足給定字符串的順序。數組

思路

按給定字符串,替換成正常順序的單詞。.net

再判斷sort以前和以後的數組是否相同。code

最終代碼

<?php
class Solution {

    /**
     * @param String[] $words
     * @param String $order
     * @return Boolean
     */
    function isAlienSorted($words, $order) {
        $order = array_flip(str_split($order));
        $alphas = str_split('abcdefghijklmnopqrstuvwxyz');
        $words = array_map(function($val) use ($order, $alphas){
            $chars = str_split($val);
            $word = [];
            foreach($chars as $char){
                $word[] = $alphas[$order[$char]];
            }
            return implode('', $word);
        }, $words);
        $originalWords = $words;
        sort($words);
        return $words == $originalWords;
    }
}

若以爲本文章對你有用,歡迎用愛發電資助。ip

相關文章
相關標籤/搜索