close
Python LeetCode 筆記:
- str.lower(),整段字串變為小寫
- rstrip:去除右邊字串
- splist:分割字串,[-1]為取最後一段字串
- chr(97):傳入ascnii字元 'a' ,(123)為z
- 十進制轉換二進制、八進制、十六進制:bin(整數)、oct(整數)、hex(整數)
題目:
58. Length of Last Word
class Solution: def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ if len(s) == 0: return 0 #rstrip 去除右邊字串 #splist分割字串,[-1]為取最後一段字串 s = s.rstrip(' ').split(' ')[-1] return len(s)
595. Big Countries
- SELECT選取資料表
- FROM選取資料庫
- WHERE 選取欄位
- OR或著
SELECT name, population, area FROM World WHERE area > 3000000 OR population > 25000000 ;
804. Unique Morse Code Words
class Solution: def uniqueMorseRepresentations(self, words): """ :type words: List[str] :rtype: int """ w=[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] #創建字典查詢a-z dict_w = {} for i in range(97,123): dict_w[chr(i)] = w[i-97] #創建列表儲存符號串、計數第一次出現的符號串 word_list=[] count = 0 for j in range(len(words)): #初始化符號串 word_string = '' #取出英文字串的每個單字 for k in words[j]: #相加符號串 word_string = word_string + dict_w[k] if word_string not in word_list: #若沒列表沒有該字符串就添加並計數 word_list.append(word_string) count += 1 return count
461. Hamming Distance
class Solution: def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ #二進制前綴'0b',使用bin轉換成二進制後去除前面兩個字元 x_str = bin(x)[2:] y_str = bin(y)[2:] #將兩字串長度相減,為較短的字串前面迴圈補'0',迴圈的範圍就是相減的數值 circle = abs(len(x_str) - len(y_str)) if len(x_str)>len(y_str): for c in range(circle): y_str = '0' + y_str else: circle = len(y_str) - len(x_str) for c in range(circle): x_str = '0' + x_str #已將兩個字串的長度相等,如果同一圈相加等於1,則代表相差1距離(1 0 或 0 1),總計數增加1 count=0 for i,j in zip(x_str,y_str): if int(i)+int(j) == 1: count += 1 return count
全站熱搜