当前位置: 首页 > 后端技术 > PHP

LeetcodePHP题解--D5804.独特的莫尔斯电码词

时间:2023-03-30 01:14:07 PHP

804。UniqueMorseCodeWords话题链接804.UniqueMorseCodeWords话题分析有多少种不同的摩尔斯电码。想法的第一步是将字符串转换为摩尔斯电码。$morse=[".-","-...","-.-","-..",".","..-.","--","....","..",".---","-.-",".-..","--","-.","---",".--""--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."];$replaced=[];foreach($wordsas$word){$chars=str_split($word);$字符串='';foreach($charsas$char){$string.=$morse[ord($char)-ord('a')];}}转换完成后存入数组,然后用array_unique函数排除。然后计数排除结果。最终代码-.","--.","....","..",".---","-.-",".-.","--","-.","---",".--.","--.-",".-.","...","-","..-","...-"".--","-..-","-.--","--.."];$replaced=[];foreach($wordsas$word){$chars=str_split($word);$字符串='';foreach($charsas$char){$string.=$morse[ord($char)-ord('a')];}$replaced[]=$string;}返回计数(array_unique($replaced));}}如果您觉得本文对您有用,欢迎使用爱发支持。如果将优化方案直接存储为数组的key,则可以省略使用array_unique去重的步骤。