classSolution: deftwoSum(self, nums, target: int): lens = len(nums) for i in range(lens): if target-nums[i] in nums[i+1:]: return [i,nums[i+1:].index(target-nums[i])+i+1] deftwoSum2(self, nums, target: int): maps = {} for i in nums: maps[i] = 1 for j in nums: if target-j in maps: f = nums.index(j) if target-j in nums[f+1:]: l = nums[f+1:].index(target-j) + f + 1 return [f, l]
classSolution: defshortestPalindrome(self, s: str) -> str: if s == "": return"" le = len(s) rs = s[::-1] for i in range(le): if s[:le-i] == rs[i:]: break return rs[:i] + s
执行用时 : 64 ms, 在String to Integer (atoi)的Python3提交中击败了88.66% 的用户
内存消耗 : 13.1 MB, 在String to Integer (atoi)的Python3提交中击败了94.70% 的用户
classSolution: defmyAtoi(self, s: str) -> int: try: s = s.split()[0] t = "" if s[0] == -: t = - s = s[1:] if s[0] == +and t == "": s = s[1:] out = 0 for i in range(len(s)): try: out = int(t+s[:i+1]) except: break
if out < -2147483648: out = -2147483648 elif out > 2147483647: out = 2147483647 return out except: return0
classSolution: defreverse(self, x: int) -> int: s = str(x) flag = "" if s[0] == -: flag = s[0] s = s[1:] ls = int(flag + s[::-1]) if ls < -2147483648or ls >2147483647: ls = 0 return ls
# L C I R # E T O E S I I G # E D H N # 之后,你的输出需要从左往右逐行读取,产生出一个新的字符串 # 比如:"LCIRETOESIIGEDHN"。
classSolution: defconvert(self, s: str, numRows: int) -> str: if numRows == 1: return s rel = "" step = numRows * 2 - 2 le = len(s) for i in range(numRows): f = i while f < le: rel += s[f] f += step mid = f-i*2 if i != numRows - 1and i != 0and mid < le: rel += s[mid] return rel