算法训练第八天

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)
相关推荐
燃于AC之乐5 小时前
我的算法修炼之路--4 ———我和算法的爱恨情仇
算法·前缀和·贪心算法·背包问题·洛谷
MM_MS11 小时前
Halcon变量控制类型、数据类型转换、字符串格式化、元组操作
开发语言·人工智能·深度学习·算法·目标检测·计算机视觉·视觉检测
独自破碎E11 小时前
【二分法】寻找峰值
算法
mit6.82411 小时前
位运算|拆分贪心
算法
ghie909012 小时前
基于MATLAB的TLBO算法优化实现与改进
开发语言·算法·matlab
恋爱绝缘体112 小时前
2020重学C++重构你的C++知识体系
java·开发语言·c++·算法·junit
wuk99812 小时前
VSC优化算法MATLAB实现
开发语言·算法·matlab
Z1Jxxx12 小时前
加密算法加密算法
开发语言·c++·算法
乌萨奇也要立志学C++12 小时前
【洛谷】递归初阶 三道经典递归算法题(汉诺塔 / 占卜 DIY/FBI 树)详解
数据结构·c++·算法
vyuvyucd13 小时前
C++引用:高效编程的别名利器
算法