python版LeetCode
算法部分
811. 子域名访问计数
class Solution:
def subdomainVisits(self, cpdomains):
"""
:type cpdomains: List[str]
:rtype: List[str]
"""
topdomain = dict()
seconddomain = dict()
thirddomain = dict()
# 创建各三级域名和访问计数的键值对
for cpd in cpdomains:
domain = cpd.split()[1]
if len(domain.split('.')) == 2:
topdomain[domain.split('.')[1]] = 0
seconddomain['.'.join(domain.split('.')[:])] = 0
if len(domain.split('.')) == 3:
topdomain[domain.split('.')[2]] = 0
seconddomain['.'.join(domain.split('.')[1:])] = 0
thirddomain['.'.join(domain.split('.')[:])] = 0
# 进行访问计数
for cpd in cpdomains:
count = int(cpd.split()[0])
domain = cpd.split()[1]
for top in topdomain:
if domain.endswith(top):
topdomain[top] += count
for second in seconddomain:
if domain.endswith(second):
seconddomain[second] += count
for third in thirddomain:
if domain.endswith(third):
thirddomain[third] += count
return [str(c) + ' ' + d for d, c in topdomain.items()] + \
[str(c) + ' ' + d for d, c in seconddomain.items()] + \
[str(c) + ' ' + d for d, c in thirddomain.items()]
709. 转换成小写字母
class Solution:
def toLowerCase(self, str):
"""
:type str: str
:rtype: str
"""
return str.lower()
557. 反转字符串中的单词 III
class Solution:
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
ls = s.split()
for i in range(len(ls)):
ls[i] = ls[i][::-1]
return ' '.join(ls)
414. 第三大的数
class Solution:
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
min_nums = min(nums)
first = min_nums
second = min_nums
third = min_nums
for n in nums:
if first < n:
first = n
for n in nums:
if n < first and second < n:
second = n
for n in nums:
if n < second and third < n:
third = n
if second == third:
return first
else:
return third
344. 反转字符串
class Solution:
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
return s[::-1]
231. 2的幂
class Solution:
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return bin(n).startswith('0b1') and bin(n).count('1') == 1
217. 存在重复元素
class Solution:
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
return len(list(set(nums))) != len(nums)
169. 求众数
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for i in set(nums):
if nums.count(i) > len(nums)/2:
return i
136. 只出现一次的数字
class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
num = 0
for i in nums:
num = num ^ i
return num
88. 合并两个有序数组
class Solution:
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
# a = 0
# b = 0
# # nums1中的0真折腾,暂时未解决
# if nums1[0]==0 and m == 0:
# nums1[:] = nums2[:]
# else:
# while b < n and a < m+n:
# if nums1[a] > nums2[b]:
# nums1[a:a] = [nums2[b]]
# b += 1
# elif nums1[a] == 0 and nums1[a-1] > 0:
# nums1[a:] = nums2[b:]
# break
# a += 1
# # 去掉nums1结尾的0
# while not nums1[-1]:
# nums1.pop()
for i in range(n):
nums1[m] = nums2[i]
m += 1
nums1.sort()
70. 爬楼梯
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
way = [0, 1, 2]
for i in range(3, n + 1):
way.append(way[i - 1] + way[i - 2])
return way[n]
26. 删除排序数组中的重复项
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# a慢指针, b快指针
a = 0
b = 0
for i in range(len(nums)):
# 如果快慢不同,则慢指针后移,再赋快指针的值
if nums[a] != nums[b]:
a += 1
nums[a] = nums[b]
# 快指针从头移动到尾
b += 1
# 如果数组为[]返回0
return a+1 if nums else 0
20. 有效的括号
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
d = {'(': ')', '[': ']', '{': '}'}
ls = []
for ss in s:
if not ls:
ls.append(ss)
else:
if d.get(ls[-1]) == ss:
ls.pop()
else:
ls.append(ss)
return False if ls else True
14. 最长公共前缀
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
# 如果含有''
if not strs or '' in strs:
return ''
# 按照字符串长度排序,看来是没必要的,
# strs = sorted(strs, key=lambda s:len(s))
# 只要找到最短的字符串中的字符,作为暂定的前缀进行判断即可
prefix = strs[0]
for s in strs:
if len(prefix) > len(s):
prefix = s
# 切片位置初置为-1
n = -1
for i in range(len(prefix)):
# 如果前缀字符是所有字符串的公共前缀,则切片位置为i,继续判断下一个字符是否匹配
if all([prefix[i] == s[i] for s in strs]) :
n = i
# 否则就找到了最长前缀,退出循环
else:
break
# 如果切片值为-1,则返回'',否则返回从最短的字符串切好的片作为最长公共前缀
return prefix[:n+1]
9. 回文数
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
x = str(x)
return x == x[::-1]
7. 整数反转
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x < 0:
# 去掉'-'
x = '-' + str(x)[1:][::-1]
elif x > 0:
x = str(x)
# 去掉结尾的0
while x.endswith('0'):
x = x[:-1]
x = x[::-1]
else:
x = '0'
# 如果x反转后溢出,或者x==0,那么就返回 0。
x = int(x)
if x < -2 ** 31 or x > 2 ** 31 - 1 or x == 0:
return 0
return x
771. 宝石与石头
class Solution:
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
n = 0
for j in J:
n += S.count(j)
return n
657. 机器人能否返回原点
class Solution:
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
return False if (moves.count('R') - moves.count('L')) or (moves.count('U') - moves.count('D')) else True
832. 翻转图像
class Solution:
def flipAndInvertImage(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
for i in range(len(A)):
A[i] = A[i][::-1]
for j in range(len(A[i])):
A[i][j] = int(not A[i][j])
return A
476. 数字的补数
class Solution:
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
num = bin(num)
cpl = list('0b')
for i in num[2:]:
if i == '1':
cpl.append('0')
else:
cpl.append('1')
return int(''.join(cpl), 2)
852. 山脉数组的峰顶索引
class Solution:
def peakIndexInMountainArray(self, A):
"""
:type A: List[int]
:rtype: int
"""
return A.index(max(A))
500. 键盘行
class Solution:
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
tab = 'qwertyuiop'
capslock = 'asdfghjkl'
shift = 'zxcvbnm'
inline = []
for W in words:
w = W.lower()
if all(c in tab for c in w) or all(c in capslock for c in w) or all(c in shift for c in w):
inline.append(W)
return inline
867. 转置矩阵
class Solution:
def transpose(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
return [[row[col] for row in A] for col in range(len(A[0]))]
349. 两个数组的交集
class Solution:
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
return list(set(nums1) & set(nums2))
680. 验证回文字符串 Ⅱ
class Solution:
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
l = 0
r = len(s) - 1
while l < r:
if s[l] != s[r]:
# 尝试跳过一个字符,直接调用判断接口,去判断剩下的即可
def judge(s, i, j):
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
return judge(s, l+1, r) or judge(s, l, r-1)
l += 1
r -= 1
return True
836. 矩形重叠
class Solution:
def isRectangleOverlap(self, rec1, rec2):
"""
:type rec1: List[int]
:type rec2: List[int]
:rtype: bool
"""
# rec1中扫描区间
# 扫描精度prec,步长prec*区间长度
x = (rec1[3]-rec1[1])
y = (rec1[2]-rec1[0])
prec = 1
# 似乎最高精度设置为1/16即可通过测试
PREC = 1/16
while prec > PREC:
i = rec1[0]
while i < rec1[2]:
j = rec1[1]
while j < rec1[3]:
if i > rec2[0] and i < rec2[2] and j > rec2[