代码随想录算法训练营day9|●151.翻转字符串里的单词 ●卡码网:55.右旋转字符串 ●28. 实现 strStr() ●459.重复的子字符串

tristan241001 / 2024-10-09 / 原文

学习资料:https://programmercarl.com/0151.翻转字符串里的单词.html

学习记录:
151.翻转字符串里的单词(感觉C语言能考虑巧妙解法,而python直接搞就对了)
c语言:把字符串整体反转,再用双指针法(slow, fast)依次翻转每一个单词,关键在于如何移除多余空格,用slow指针找到要替换到的位置,用fast指针获取目标字母,并在str[fast]前面加个空格
python语言:split函数+双指针

点击查看代码
class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        words = s.split()
        left, right = 0, len(words)-1
        while left<right:
            words[left], words[right] = words[right], words[left]
            left += 1
            right -= 1
        return " ".join(words)

卡码网 55.左旋转字符串(python解法很简单,就切片再调换顺序)

点击查看代码
k = int(input())
s = input()
s=s[len(s)-k:] + s[:len(s)-k]
print(s)

PS:
没写28和459两道题, KMP算法先放一放
卡码网 要写输入格式(k=int(input()))
秋招好难,核动力好翘,吃了酸萝卜鱼蛙(味道一般哦
双指针方法贯通字符串、数组、链表
字符串章节 over~