28. Find the Index of the First Occurrence in a String
- 经典KMP算法
class Solution(object):
def strStr(self, haystack, needle):
if len(needle) == 0:
return 0
nextList = self.getNext(needle)
j = 0
for i in range(0, len(haystack)):
while j > 0 and haystack[i] != needle[j]:
j = nextList[j - 1]
if haystack[i] == needle[j]:
j += 1
if j == len(needle):
# 返回满足条件的字符串的第一个位置
return i - len(needle) + 1
return -1
def getNext(self, needle):
j = 0
# 创建list
nextList=['' for i in range(len(needle))]
# 设第一个值为0
nextList[0] = 0
for i in range(1, len(needle)):
# 如果前后缀的最后一个字符不相等,则j(持续)向前跳
while j > 0 and needle[j] != needle[i]: # j指向前缀末尾位置,i指向后缀末尾位置
j = nextList[j - 1]
# 如果前后缀的最后一个字符相等,则j向后移动一位
if needle[i] == needle[j]:
j += 1
# 每次比较结束,前缀表都记录该位置的最长相等前后缀长度
nextList[i] = j
return nextList
459. Repeated Substring Pattern
- 原字符串长度的长度,为L1
- 原字符串的长度减去最长相等(前)后缀的长度,为L2
- L1能够整除L2,且最长相等前后缀的长度不为0,则原字符串是由重复子串构成
class Solution(object):
def repeatedSubstringPattern(self, s):
sLength = len(s)
if sLength == 0:
return False
nextList = self.getNext(s)
lastPos = sLength - 1
compensate = sLength - nextList[lastPos]
if nextList[lastPos] != 0 and sLength % compensate == 0:
return True
return False
def getNext(self, needle):
j = 0
nextList=['' for i in range(len(needle))]
nextList[0] = 0
for i in range(1, len(needle)):
while j > 0 and needle[j] != needle[i]: # j指向前缀末尾位置,i指向后缀末尾位置
j = nextList[j - 1]
if needle[i] == needle[j]:
j += 1
nextList[i] = j
return nextList
232. Implement Queue using Stacks
class MyQueue(object):
def __init__(self):
self.in_stk = []
self.out_stk = []
# Push element x to the back of queue...
def push(self, x):
self.in_stk.append(x)
# Remove the element from the front of the queue and returns it...
def pop(self):
self.peek()
return self.out_stk.pop()
# Get the front element...
def peek(self):
if not self.out_stk:
while self.in_stk:
self.out_stk.append(self.in_stk.pop())
return self.out_stk[-1]
# Return whether the queue is empty...
def empty(self):
return not self.in_stk and not self.out_stk
225. Implement Stack using Queues
class MyStack(object):
def __init__(self):
self._queue = collections.deque()
# 新元素从左边入栈
def push(self, x):
q = self._queue
q.append(x)
for _ in range(len(q) - 1):
q.append(q.popleft())
# 左边出栈
def pop(self):
return self._queue.popleft()
# 弹出头元素
def top(self):
return self._queue[0]
# 判断是否为空
def empty(self):
return len(self._queue) == 0