继上篇Leetcode题Leetcode题medium120/152/153/162/209/216/228/229/238/287,Python多种解法(六),完成了前三百题里关于Array的easy和medium题,原先的想法是继续困难题的Array,但是说实在,在中等题的解答过程中,发现自己对算法的很多不熟悉,包括动态规范、贪心、回溯等等,觉得以现在的水平去完成困难的,大概也就是看眼题目,看眼答案的程度,想想还是算了,还是尽快完成所有的前300题,尽快开始二刷先。
同时,这段时间一直在看王争老师的《数据结构与算法之美》,收货颇多,争取理论知识学完+刷题同步进行。写博客也写了半年左右,目前还是把博客当做自己的笔记在做,下一篇决定分享下这段时间的学习以及接下来的学习,并且分享一些不错的书籍和课程,就当是对未来的规划。
那本篇文章开始leetcode前三百题的easy题分享。
class MySolution(object):
"""
我的想法很简单,定义个字典来匹配,然后遍历,当左边的值小于右边的值则说明加上对应的负数,反之加正数,最后
的一个数一定是正数,当然效率也是蛮低的
Runtime: 92 ms, faster than 34.34% of Python online submissions for Roman to Integer.
Memory Usage: 11.7 MB, less than 5.47% of Python online submissions for Roman to Integer.
"""
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
sum = 0
for i in range(len(s)-1):
if self.change(s[i]) < self.change(s[i+1]):
sum += -self.change(s[i])
else:
sum += self.change(s[i])
return sum+self.change(s[-1])
def change(self,alp):
change_dict = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
return change_dict[alp]
class Solution(object):
"""
思路是相同的,不过讨论区的写的更pythonic,直接定义一个I的值,然后从后往前遍历,时间复杂度也是达到了100%
Runtime: 60 ms, faster than 100.00% of Python online submissions for Roman to Integer.
Memory Usage: 11.9 MB, less than 5.47% of Python online submissions for Roman to Integer.
"""
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
d = {'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1}
res, p = 0, 'I'
for c in s[::-1]:
res, p = res - d[c] if d[c] < d[p] else res + d[c], c
return res
class Solution(object):
"""
通过zip把每一个首字母拼接,然后判断set后是否为1即可知道是否相等,要注意的是当全部匹配成功后,取列表strs里面长度最短的数
Runtime: 24 ms, faster than 64.14% of Python online submissions for Longest Common Prefix.
Memory Usage: 12.1 MB, less than 5.66% of Python online submissions for Longest Common Prefix.
"""
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ''
for i, v in enumerate(zip(*strs)):
if len(set(v)) > 1:
return strs[0][:i]
else:
return min(strs)
class Solution2(object):
"""
直接用暴力匹配法,取列表第一个单词,从后往前遍历,逐一匹配所有单词,符合即返回
Runtime: 28 ms, faster than 38.54% of Python online submissions for Longest Common Prefix.
Memory Usage: 12 MB, less than 5.66% of Python online submissions for Longest Common Prefix.
"""
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
prefix = strs[0] if strs else ''
while True:
if all(s.startswith(prefix) for s in strs):
return prefix
prefix = prefix[:-1]
class Solution(object):
"""
看到找括号,第一反应就是通过stack来做,先进后出的数据结构完美解决,每次到右括号时判断左括号和右括号是否一致就行了,
因为([ )]明显不存在,一定要是([])才行,所以每次pop()最先的就行了。
Runtime: 24 ms, faster than 54.47% of Python online submissions for Valid Parentheses.
Memory Usage: 12 MB, less than 5.20% of Python online submissions for Valid Parentheses.
"""
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
left, right, stack= "({[", ")}]", []
for item in s:
if item in left:
stack.append(item)
else:
if not stack or left.find(stack.pop()) != right.find(item):
return False
return not stack
class Solution2(object):
"""
讨论区的另一种解法,用字典来做,本质是一致的~
Runtime: 24 ms, faster than 54.47% of Python online submissions for Valid Parentheses.
Memory Usage: 12.1 MB, less than 5.20% of Python online submissions for Valid Parentheses.
"""
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
dict = {"]":"[", "}":"{", ")":"("}
for char in s:
if char in dict.values():
stack.append(char)
elif char in dict.keys():
if stack == [] or dict[char] != stack.pop():
return False
else:
return False
return stack == []
class Solution(object):
"""
直接遍历判断当前的haystack包含的与needle是否相等即可
Runtime: 20 ms, faster than 80.25% of Python online submissions for Implement strStr().
Memory Usage: 11.8 MB, less than 19.41% of Python online submissions for Implement strStr().
"""
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
for i in range(len(haystack)-len(needle)+1):
if haystack[i:i+len(needle)] == needle:
return i
return -1
class Solution(object):
"""
理解了题意即懂如何做,题意是依据上一个字符串来推导下一个字符串,第一个字符串是"1",所以第二个就是1个1,即"11",
第三个就是2个1,即"21",第四个就是1个2,1个1,即"1211";
解法就是遍历需要得到的答案位于第几个,然后针对每一个去求得它的值
Runtime: 24 ms, faster than 64.32% of Python online submissions for Count and Say.
Memory Usage: 11.8 MB, less than 5.40% of Python online submissions for Count and Say.
"""
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
res = '1'
for _ in range(n - 1):
res = self.helper(res)
return res
def helper(self, n):
count, i, res = 1, 0, ""
while i < len(n) - 1:
if n[i] == n[i + 1]:
count += 1
else:
res += str(count) + n[i]
count = 1
i += 1
res += str(count) + n[i]
return res
class Solution2(object):
"""
高阶解法,用正则来完成
Runtime: 24 ms, faster than 64.32% of Python online submissions for Count and Say.
Memory Usage: 12 MB, less than 5.40% of Python online submissions for Count and Say.
"""
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
s = '1'
for _ in range(n - 1):
s = ''.join(str(len(group)) + digit
for group, digit in re.findall(r'((.)\2*)', s))
return s
class Solution3(object):
"""
trick解法,用itertools来完成
Runtime: 28 ms, faster than 32.56% of Python online submissions for Count and Say.
Memory Usage: 12 MB, less than 5.40% of Python online submissions for Count and Say
"""
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
s = '1'
for _ in range(n - 1):
s = ''.join(str(len(list(group))) + digit
for digit, group in itertools.groupby(s))
return s
class Solution(object):
"""
直接利用python的split获取最后一个即可
Runtime: 24 ms, faster than 32.47% of Python online submissions for Length of Last Word.
Memory Usage: 11.9 MB, less than 5.42% of Python online submissions for Length of Last Word.
"""
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
return len(s.split()[-1]) if s.split() else 0
class Solution2(object):
"""
利用rstrip可以把判断语句都省略
Runtime: 20 ms, faster than 70.08% of Python online submissions for Length of Last Word.
Memory Usage: 11.8 MB, less than 5.42% of Python online submissions for Length of Last Word.
"""
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
return len(s.rstrip().split(' ')[-1])
class Solution(object):
"""
0b+'a' 获取二进制的值,比如0b11,通过eval获取字符串表达式的值为3,相加后再通过bin转为二进制;
实际上等价于:bin(int(a, 2) + int(b, 2))[2:]
Runtime: 24 ms, faster than 86.44% of Python online submissions for Add Binary.
Memory Usage: 11.9 MB, less than 5.18% of Python online submissions for Add Binary.
"""
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return bin(eval('0b'+a)+eval('0b'+b))[2:]
# return bin(int(a, 2) + int(b, 2))[2:]
class Solution2(object):
"""
感觉这才是标准不取巧解法,直接通过二进制位数相加判断获取结果,方法还是很巧妙,mark一下
Runtime: 32 ms, faster than 44.25% of Python online submissions for Add Binary.
Memory Usage: 12.1 MB, less than 5.18% of Python online submissions for Add Binary.
"""
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
i,j,carry,res=len(a)-1,len(b)-1,0,''
while i>=0 or j>=0 or carry > 0:
if i>=0:
carry += int(a[i])
i -= 1
if j>=0:
carry += int(b[j])
j-=1
res = str(carry%2) + res
carry //= 2
return res
class Solution(object):
"""
标准解法,通过while循环左侧和右侧,当碰到非字母数字就跳过,然后比对左右侧是否相等
Runtime: 44 ms, faster than 64.81% of Python online submissions for Valid Palindrome.
Memory Usage: 12.2 MB, less than 56.30% of Python online submissions for Valid Palindrome.
"""
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
l,r = 0,len(s)-1
while l < r:
while l
本次分享到此为止,感谢观看~