Leetcode PHP題解--D5 804. Unique Morse Code Words
804. Unique Morse Code Words
題目連結
題目分析
這個題目要求算出把給定陣列中的字串轉換成摩爾斯碼後,有多少個不同的摩爾斯碼。
思路
第一步需要把字串轉換成摩爾斯碼。
$morse = [ ".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--", "-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.." ]; $replaced = []; foreach($words as $word){ $chars = str_split($word); $string = ''; foreach($chars as $char){ $string .= $morse[ord($char)-ord('a')]; } }
轉換完成後存進陣列內,再用array_unique函式排除。再count排除結果即可。
最終程式碼
<?php class Solution { function uniqueMorseRepresentations($words) { $morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]; $replaced = []; foreach($words as $word){ $chars = str_split($word); $string = ''; foreach($chars as $char){ $string .= $morse[ord($char)-ord('a')]; } $replaced[] = $string; } return count(array_unique($replaced)); } }
若覺得本文章對你有用,歡迎用愛發電 資助。
優化方案
- 直接存為陣列的鍵則可以省去用array_unique去重的步驟。