算法训练第八天

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)
相关推荐
梦想画家1 小时前
Apache AGE实战指南:从Cypher语法到核心图算法
算法·cypher·apache age
刀法如飞1 小时前
Go数组去重的20种实现方式,AI时代解决问题的不同思路
后端·算法·go
旖-旎2 小时前
深搜练习(N皇后)(10)
c++·算法·深度优先·力扣
Controller-Inversion3 小时前
322. 零钱兑换
算法
头发够用的程序员3 小时前
C++和Python面试经典算法汇总(一)
开发语言·c++·python·算法·容器·面试
淡海水3 小时前
【AI模型】模型量化技术详解
人工智能·算法·机器学习
炸膛坦客3 小时前
嵌入式 - 数据结构与算法:(1-1)数据结构 - 顺序表(Sequential List)
数据结构·算法·嵌入式
水龙吟啸3 小时前
数据结构与算法随机复习–Day1
数据结构·c++·算法
生成论实验室3 小时前
《事件关系阴阳博弈动力学:识势应势之道》第八篇:认知与反思关系——探索、定位与延续
人工智能·算法·架构·知识图谱·创业创新
YaraMemo4 小时前
一文带你区分全局最优解和帕累托最优解
算法·5g·信息与通信·信号处理