阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。
1. Char removal
Strings are immutable, but can slice strings using [start:stop:step] (得到切片结果,不应称为可变嵌套对象的深拷贝).
1.1 Remove a/some particular chars from a string
example: input = “student”, remove “u” and “n” -> output “stdet”
易错点:“stuuudent”,未考虑重复字符
1.1.1 快慢指针
lst = ['s', 't', 'u', 'd', 'e', 'n', 't']
i
j
lst = ['s', 't', 'd', 'e', 't', 'n', 't']
i
j- i(slow): all letters to the left-hand side of i (not include i) are all processed letters that should be kept.
- j(fast): the letter being processed.
All letters in [i, j-1] are all area that we don’t care.
def remove0(string):
lst = list(string)
i, j = 0, 0
while j < len(lst):
if lst[j] not in ['u', 'n']:
lst[i] = lst[j]
i += 1
j += 1
return "".join(lst[:i]) # "$".join(lst[:i]) -> "s$t$d$e$t"1.1.2 Use list
def remove1(string):
res = []
for ch in string:
if ch not in ['u', 'n']:
res.append(ch)
return "".join(res)1.1.3 Bad solution
字符串串联需要复制所有字符,创造了新的string,这是一个操作(其中N和M是输入字符串的大小)
(峰值额外空间;累计复制量可达二次)
def remove2(string):
res = ""
for ch in string:
if ch not in ['u', 'n']:
res += ch
return res1.2 Remove all leading/trailing and duplicate empty spaces
input = ”_ _ _ abc_ _ de_ _ de_ _“
output = “abc_de_de”
solution:快慢指针
Initialization:
lst = "_ _ a b c _ _ d e _ _ d e _ _ "
i
j
lst = "a b c _ d e _ d e _ _ d e _ _ "
i
jTermination:
lst = "a b c _ d e _ d e _ _ d e _ _ "
i
jInitialization: j = 0, i = 0
For each step:
- case 1: lst[j] == ”_” and i = 0, ignore
- case 2: lst[j] != ”_”, keep
- case 3: lst[j] == ”_” and i != 0 and lst[i-1] != ”_”, keep
- case 4: lst[j] == ”_” and i != 0 and lst[i-1] == ”_”, ignore
Termination: j = n
- Post-processing: i > 0 and lst[i - 1] == ”_”, then i -= 1
def remove_spaces(string):
if not string:
return string
lst = list(string)
i, j = 0, 0
while j < len(string):
# if not (lst[j] == " " and (i == 0 or lst[i - 1] == " ")):
if lst[j] != " " or (i != 0 and lst[i - 1] != " "):
lst[i] = lst[j]
i += 1
j += 1
# remove trailing empty space
if i > 0 and lst[i - 1] == " ":
i -= 1
"""
IndexError: list index out of range
if lst[slow] == " " and lst[slow - 1] == " ":
"""
return "".join(lst[:i])
# Test case
print(remove_spaces(' ILove Yahoo'))ILove Yahoo
2. Char De-duplication
2.1 Remove duplicated and adjacent letters
“aabbazw” => “abazw”
2.1.1 slow, fast
Initialization: j = 1, i = 1
- case 1: lst[j] == lst[i-1], ignore (j += 1)
- case 2: lst[j] != lst[i-1], keep lst[i] = lst[j], i += 1, j += 1
def remove_duplicate0(string):
if not string or len(string) < 2:
return string
lst = list(string)
slow, fast = 1, 1
while fast < len(lst):
if lst[fast] != lst[slow - 1]:
lst[slow] = lst[fast]
slow += 1
fast += 1
return "".join(lst[:slow])2.1.2 list
def remove_duplicate1(string):
if not string or len(string) < 2:
return string
fast = 0
lst = []
while fast < len(string):
if len(lst) == 0 or lst[-1] != string[fast]:
lst.append(string[fast])
fast += 1
return "".join(lst)2.2 Char de-duplication adjacent letters repeatedly
abbbbaz -> aaz -> z
solution: Stack
- case 1: a[f] != stack.top(), then stack.push(a[f]), f += 1
- case 2: a[f] == stack.top(), keep moving f until a[f] != stack.top(), stack.pop()
def remove_duplicate(string):
if not string or len(string) < 1:
return string
stack = []
fast = 0
while fast < len(string):
if len(stack) > 0 and string[fast] == stack[-1]:
while fast < len(string) and stack[-1] == string[fast]:
fast += 1
stack.pop()
else:
stack.append(string[fast])
fast += 1
return "".join(stack)3. Reverse
3.1 reverse string “I love Yahoo” -> “Yahoo love I”
method 1: split -> reverse -> concat
method 2:
- reverse whole string “oohaY evol I”
- reverse every single word “Yahoo love I”
def reverse_helper(lst, left, right):
while left < right:
lst[left], lst[right] = lst[right], lst[left]
left += 1
right -= 1
def reverse_string(string):
lst = list(string)
reverse_helper(lst, 0, len(lst) - 1)
i = 0
left = 0
right = 0
while i < len(lst):
if i == len(lst) - 1 or lst[i + 1] == " ":
right = i
reverse_helper(lst, left, right)
left = i + 2
i += 1
return "".join(lst)4. Substring
检查一个字符串是否为另一个字符串的子串
-
method 1: brute-force
-
method 2: Rabin-Karp: avg , worst
Initializaton: compute hash(s2) — O(n), n = len(s2)
each time we move sliding window: m = len(s1)
time complexity for each step O(1) # 大整数的加减乘除不是常数
total: O(m + n)- s2 = “cde”
- s1 = “abcde”
- s2 = “cde”
class RavinKarp(object):
def __init__(self):
self.base = 26
self.mod = 997
def strstr(self, haystack, needle):
if len(needle) > len(haystack):
return -1
hay_hash, nhash = 0, 0
# power is the weight on the highest digit of the needle
power = 1
for i in range(len(needle)):
power = power * self.base % self.mod if i != 0 else 1
hay_hash = (hay_hash * self.base + ord(haystack[i])) % self.mod
nhash = (nhash * self.base + ord(needle[i])) % self.mod
for i in range(len(needle), len(haystack)):
if hay_hash == nhash and needle == haystack[i - len(needle): i]:
return i - len(needle)
hay_hash -= (power * ord(haystack[i - len(needle)])) % self.mod
if hay_hash < 0:
hay_hash += self.mod
hay_hash = (hay_hash * self.base + ord(haystack[i])) % self.mod
if hay_hash == nhash and needle == haystack[len(haystack) - len(needle):]:
return len(haystack) - len(needle)
return -1