344.反转字符串
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。
不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。
方法一
使用切片
class Solution(object):
def reverseString(self, s):
"""
:type s: List[str]
:rtype: None Do not return anything, modify s in-place instead.
"""
s[::]=s[::-1]
方法二
使用双指针
class Solution(object):
def reverseString(self, s):
"""
:type s: List[str]
:rtype: None Do not return anything, modify s in-place instead.
"""
left=0
right=len(s)-1
while left<right:
s[left],s[right]=s[right],s[left]
left+=1
right-=1
路径加密
使用replace函数
class Solution(object):
def pathEncryption(self, path):
"""
:type path: str
:rtype: str
"""
return path.replace("."," ")
151.翻转字符串里的单词
给定一个字符串,逐个翻转字符串中的每个单词。
方法一
使用切片索引
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
s=s.strip(" ")
s=s[::-1]
s= ' '.join(i[::-1] for i in s.split())
return s
方法二
使用双指针法
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
word=s.split()
left=0
right=len(word)-1
while left<right:
word[left],word[right]=word[right],word[left]
left+=1
right-=1
return ' '.join(word)
28. 实现 strStr()
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1: 输入: haystack = “hello”, needle = “ll” 输出: 2
方法:使用KMP算法
寻找最长相等前后缀,以此来寻找匹配错误的字符的前一个字符。
class Solution:
def getNext(self, next, s) :
j = 0
next[0] = 0
for i in range(1, len(s)):
while j > 0 and s[i] != s[j]:
j = next[j - 1]
if s[i] == s[j]:
j += 1
next[i] = j
def strStr(self, haystack, needle):
if len(needle) == 0:
return 0
next = [0] * len(needle)
self.getNext(next, needle)
j = 0
for i in range(len(haystack)):
while j > 0 and haystack[i] != needle[j]:
j = next[j - 1]
if haystack[i] == needle[j]:
j += 1
if j == len(needle):
return i - len(needle) + 1
return -1
459.重复的子字符串
给定一个非空的字符串,判断它是否可以由它的一个子串重复多次构成。给定的字符串只含有小写英文字母,并且长度不超过10000。
示例 1:
输入: “abab”
输出: True
解释: 可由子字符串 “ab” 重复两次构成。
方法
使用KMP算法
class Solution(object):
def getNext(self,next,s):
j=0
next[0]=0
for i in range(1,len(s)):
while j>0 and s[i]!=s[j]:
j=next[j-1]
if s[i]==s[j]:
j+=1
next[i]=j
return next
def repeatedSubstringPattern(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) == 0:
return False
next = [0] * len(s)
self.getNext(next, s)
if next[-1] != 0 and len(s) % (len(s) - next[-1]) == 0:
return True
return False