leetcode--804. Unique Morse Code Words

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/zhouky146/article/details/89332606

自己的做法:

把其变为字典:

def uniqueMorseRepresentations(words):
   di={'a':".-",'b':"-...",'c':"-.-.",'d':"-..",'e':".",'f':"..-.",'g':"--.",'h':"....",'i':"..",'j':".---",'k':"-.-",'l':".-..",'m':"--",'n':"-.",'o':"---",'p':".--.",'q':"--.-",'r':".-.",'s':"...",'t':"-",'u':"..-",'v':"...-",'w':".--",'x':"-..-",'y':"-.--",'z':"--.."}
   result=[]
   for w in words:
        temp=""
        for i in w:
            temp=temp+di[i]
        result.append(temp)
   result2=[]
   for i in result:
        if i not in result2:
            result2.append(i)
   return len(result2)

exm= ["gin", "zen", "gig", "msg"]
print(uniqueMorseRepresentations(exm))

别人的做法:

class Solution:	
	def uniqueMorseRepresentations(self, words: List[str]) -> int:
	   result_letter = ""
       result_word = []
		
        morse_arr = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]

        for word in words:
            for letter in word:
                result_letter = result_letter +morse_arr[ord(letter)-97]
            result_word.append(result_letter)
            result_letter = ""              
               
        return(len(set(result_word)))

ord()函数是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值,如果所给的 Unicode 字符超出了你的 Python 定义范围,则会引发一个 TypeError 的异常。

a=97

猜你喜欢

转载自blog.csdn.net/zhouky146/article/details/89332606