算法思路:这道题就是一个栈就能解决,不多说,碰到’(’,’[’,’{’,入栈,遇到’)’,’]’,’}’。弹出栈顶的元素,匹配是否是一对,不是则结束输出无效。如果所有的输入完成,栈不为空,输出无效,其它情况都是有效的
class Solution:
def isValid(self, s: 'str') -> 'bool':
if s =="":
return True
char_list = []
for char in s:
if char =='(' or char == '[' or char == '{':
char_list.append(char)
elif char ==')':
if len(char_list) and char_list[-1]=='(':
char_list.pop()
else:
return False
elif char == ']':
if len(char_list) and char_list[-1]=='[':
char_list.pop()
else:
return False
elif char == '}':
if len(char_list) and char_list[-1]=='{':
char_list.pop()
else:
return False
if len(char_list) == 0:
return True
else:
return False
LeetCode21合并两个有序链表
算法思路:使用归并排序的思路,比较两个节点值的大小,小的则插入新的链表中,依次比较,直到一条链表比较完成,将另外一条链表加入到新的链表尾。
class Solution:
def mergeTwoLists(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode':
r = ListNode(0)
head = r
while l1 and l2:
if l1.val <= l2.val:
head.next = l1
head = head.next
l1 = l1.next
else:
head.next = l2
head = head.next
l2 = l2.next
if l1:
head.next = l1
if l2:
head.next = l2
return r.next
LeetCode26删除排序数组中的重复项
算法思路:哈希思想,将出现的元素作为键,将出现次数记录下来。再遍历一边哈希表,将出现次数大于一的key写到nums中。
tips:题目描述没有说清楚,事实上是需要返回最后nums的长度,不是nums
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
c = {}
for i in nums:
c.setdefault(i,0)
c[i] += 1
j = 0
for key in c:
if c[key] >= 1:
nums[j] = key
j +=1
return j
LeetCode27移除元素
算法思路:思路和上题一样。
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
c = {}
count = 0
for i in nums:
if i != val:
c.setdefault(i,0)
c[i] += 1
count += 1
j = count
for key in c:
for i in range(0,c[key]):
nums[count-1] = key
count -=1
return j
LeetCode28实现strStr()
算法思路:这道题就是考察暴力搜索算法和kmp算法的。kmp算法的关键在于理解next数组的生成,next[i]代表子串s[0,…i]的最长相等前后缀的前缀的最后一位下标。
而next数组的求解过程如下:
1.初始化next数组,并且j=next[0] = -1。
2.遍历 i从1到length-1
3.不断令j = next[j],直到j=-1或者s[i] = s[j+1]
4.如果s[i] = s[j+1],则next[i] = j+1,否则next[i] = j
而kmp将模式串和子串进行匹配的过程就和求解next数组一致,唯一不同的就是从模式串的第一位开始,而求解next数组是从第二位开始。
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
len_needle = len(needle)
len_haystack = len(haystack)
index = 0
if len_needle == 0:
return index
def getnext(length_pattern,pattern):
j = - 1
next = list(range(len_needle))
next[0] = -1
for i in range(1,length_pattern):
while(j != -1 and pattern[i] != pattern[j+1]):
j = next[j]
if pattern[i] == pattern[j+1]:
j += 1
next[i] = j
return next
next = getnext(len_needle,needle)
print(next)
j = -1
for i in range(len_haystack):
while(j != -1 and haystack[i] != needle[j+1]):
j = next[j]
if haystack[i] == needle[j+1]:
j += 1
if j == len_needle -1:
index = i + 1 - len_needle
return index
return -1