344.反转字符串
思路:
我们用双指针来解,i指向开头,j指向结尾,当i小于j时,每次交换s[i],s[j]即可。
代码:
python
class Solution(object):
def reverseString(self, s):
"""
:type s: List[str]
:rtype: None Do not return anything, modify s in-place instead.
"""
i = 0
j = len(s)-1
while i<j:
s[i],s[j] = s[j],s[i]
i+=1
j-=1
return s
541.反转字符串II
思路:
因为python中的字符串是不可变类型,因此我们需要将字符串转为字符数组,然后再进行修改。我们使用双指针和滑动窗口算法,使用i指向滑动窗口的起始位置,j指向滑动窗口的最后一个元素,然后反转。只是最后需要判断结束循环时滑动窗口的状态。
代码:
python
class Solution(object):
def reverse_str(self,s,left,right):
i = left
j = right
while i<j:
s[i],s[j] = s[j],s[i]
i+=1
j-=1
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
i = 0
j = 0
str = list(s)
while j < len(str)-1:
while j - i + 1 < 2 * k and j < len(str)-1:
j += 1
if j==len(str)-1:
break
self.reverse_str(str, i, i + k - 1)
i = j + 1
j += 1
if j-i+1<k:
self.reverse_str(str,i,j)
else:
self.reverse_str(str, i, i + k - 1)
ans = "".join(str)
return ans
54.替换数字
思路:
我们使用的是python,因此必须要开一个辅助数组,那这样就很简单了,我们只需要遍历字符串放入数组,如果是数字,就放入一个number就好了。
代码:
python
def main(s):
str = list(s)
new_str = []
for i in str:
if ord(i)>=ord('0') and ord(i)<=ord('9'):
new_str.append('number')
else:
new_str.append(i)
print(''.join(new_str))
if __name__=='__main__':
s = input()
main(s)