大家好,從本次開始,為大家推薦200道大資料面試常考Leetcode演算法題,每篇更新5篇,艾瑞巴迪和我一起刷起來!!
200道大資料面試常考Leetcode演算法題06-Z字形變換
Leetcode原題為
class Solution: def convert(self, s: str, numRows: int) -> str: n = numRows * 2 - 2 # 判斷z字形回圈的周期規律為:行數*2減去頭尾兩個 if numRows < 2: # 判斷給出的z字形行數小于2時,z字形無法成型 return s # 回傳原陣列,做安全容錯處理 result = [""]*numRows # 用一個["","",""]裝納每行的資料,這里是三行 for i, char in enumerate(s): # 回圈每個索引跟值 index = i % n # 當前字符的索引整除周期的值 x = min(index, n - index) # 找出最小的值,周期有峰值 result[x] += char # 把當前的最小的索引值為行號,然后把當前值添加到當前索引行 return "".join(result) # 最后3行字符拼接在一起
200道大資料面試常考Leetcode演算法題07-整數反轉
Leetcode原題:
題解為:
class Solution: def reverse(self, x: int) -> int: # 判斷對正數反轉時 if x>=0: # 整型變成字串用切片,-1表示反轉 ans=int(str(x)[::-1]) else: # 假如是負數的時候則先變為負整數,然后在反轉 ans=-int(str(-x)[::-1]) # 判斷反轉后的數符合32位范圍 if -2**31<=ans<=2**31-1: return ans return 0
200道大資料面試常考Leetcode演算法題08-字串轉換整數 (atoi)
Leetcode原題:
題解為:
import re class Solution: def myAtoi(self, str: str) -> int: INT_MAX = 2147483647 INT_MIN = -2147483648 str = str.lstrip() #清除左邊多余的空格 num_re = re.compile(r'^[\+\-]?\d+') #設定正則規則 num = num_re.findall(str) #查找匹配的內容 num = int(*num) #由于回傳的是個串列,解包并且轉換成整數 return max(min(num,INT_MAX),INT_MIN) #回傳值
200道大資料面試常考Leetcode演算法題09-回文數
Leetcode原題:
題解為:
class Solution: def isPalindrome(self, x: int) -> bool: # 判斷對正數反轉時 if x>=0: # 整型變成字串用切片,-1表示反轉 ans=int(str(x)[::-1]) # 直接反轉對比是否等于原數 if ans == x: return True # 其他情況一律不符合 return False
200道大資料面試常考Leetcode演算法題10-正則運算式匹配
Leetcode原題為:
題解為:
class Solution(object): def isMatch(self, s, p) -> bool: if not s and not p: return True if len(s) > 0 and not p: return False # 當模式中的第二個字符是“*”時: if len(p) > 1 and p[1] == '*': # 如果字串第一個字符跟模式第一個字符匹配,可以有3種匹配方式: if len(s) > 0 and (s[0] == p[0] or p[0] == '.'): # 1、模式后移2字符,相當于x*被忽略; # 2、字串后移1字符,模式后移2字符; # 3、字串后移1字符,模式不變,即繼續匹配字符下一位,因為*可以匹配多位; return self.isMatch(s[:], p[2:]) or self.isMatch(s[1:], p[2:]) or self.isMatch(s[1:], p[:]) # 如果字串第一個字符跟模式第一個字符不匹配 else: # 模式后移2個字符,繼續匹配, return self.isMatch(s, p[2:]) # 當模式中的第二個字符不是“*”跟第一個字符和模式中的第一個字符相匹配時: if len(s) > 0 and (p[0] == s[0] or p[0] == '.'): # 那么字串和模式都后移一個字符,然后匹配剩余的, return self.isMatch(s[1:], p[1:]) # 如果字串第一個字符和模式中的第一個字符相不匹配,直接回傳false, return False
好啦,這期的分享到這里結束啦!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/290215.html
標籤:其他
下一篇:大資料穩定性體系建設





