字符串章节 leetcode 思路&实现

344. 反转字符串

思路:.reverse()秒了

或者前后指针依次交换即可

python 复制代码
class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        left,right = 0,len(s)-1
        while left<right:
            s[left],s[right] = s[right],s[left]
            left += 1
            right -= 1

541. 反转字符串 II

思想:准备分类讨论,但是比较复杂,也能做。注意要转成列表进行切片,字符串无法修改

null 复制代码
class Solution:
    def reverseStr(self, s: str, k: int) -> str:
        n = len(s)
        s = list(s)
        i = 0
        while n-i >= 2*k:
            s[i:i+k] = s[i:i+k][::-1]
            i+=2*k
        if n-i<2*k:
            s[i:i+k] = s[i:i+k][::-1]
        return ''.join(s)

考虑当切片超出列表长度时,Python会自动截断

null 复制代码
class Solution:
    def reverseStr(self, s: str, k: int) -> str:
        n = len(s)
        s = list(s)
        for i in range(0,n,2*k):
            s[i:i+k] = s[i:i+k][::-1]
        return ''.join(s)
  1. 替换数字(第八期模拟笔试)

思路:字符串转化为list,遍历list,找到ord(i)在ord(0)和ord(9)之间的,就执行列表的切片相加。最后返回即可

python 复制代码
s = list(input())
n = len(s)

for i in range(n):
    if 48<= ord(s[i]) <=57:
        s = s[:i]+['number']+s[i+1:]
print(''.join(s))
python 复制代码
s = list(input())
n = len(s)

for i in range(n):
    if ord('0')<= ord(s[i]) <=ord('9'):
        s = s[:i]+['number']+s[i+1:]
print(''.join(s))

151. 反转字符串中的单词

思路:无所谓,.split()会去除所有的空格,无需担心

null 复制代码
class Solution:
    def reverseWords(self, s: str) -> str:
        sen = list(s.split())
        sen.reverse()
        return ' '.join(sen)
  1. 右旋字符串(第八期模拟笔试)

思路:操作题,切片相加就行

null 复制代码
k = int(input())
s = list(input())

s = s[-k:]+s[:len(s)-k]
print(''.join(s))

28. 找出字符串中第一个匹配项的下标

思路:短的字符串切了去长的字符串里面找,简明易懂,且正确(KPM叽里咕噜说啥呢)

python 复制代码
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        m,n = len(haystack),len(needle)
        for i in range(0,m-n+1):
            if needle == haystack[i:i+n]:
                return i
        else:
            return -1

459. 重复的子字符串

思路:简单题也没思路吗,可恶

s如果有两个及以上的子集,那么s一定在s+s去头去尾里面。防止s搜到他自己。不用find哈,万一在0位置检索到很尴尬

python 复制代码
class Solution:
    def repeatedSubstringPattern(self, s: str) -> bool:
        new_s = s + s
        return True if s in new_s[1:len(new_s)-1] else False
相关推荐
郝学胜-神的一滴7 小时前
[力扣 20] 栈解千愁:有效括号序列的优雅实现与深度解析
java·数据结构·c++·算法·leetcode·职场和发展
林姜泽樾7 小时前
python入门第六课,其他字符串格式化和input
开发语言·python·pycharm
yunpeng.zhou7 小时前
深度理解agent与llm之间的关系、及mcp与skill的区别
人工智能·python·ai
AlenTech7 小时前
128. 最长连续序列 - 力扣(LeetCode)
算法·leetcode·职场和发展
小江的记录本7 小时前
【Docker】 Docker 全平台部署(Linux / Windows / MacOS)与 前后端分离项目 容器化方案
java·linux·windows·http·macos·docker·容器
田梓燊7 小时前
leetcode 无重复字符的最长子串
算法·leetcode·职场和发展
智算菩萨7 小时前
【Pygame】第14章 摄像机系统与游戏视口控制技术
python·游戏·pygame
武藤一雄7 小时前
深入拆解.NET内存管理:从GC机制到高性能内存优化
windows·microsoft·c#·.net·wpf·.netcore·内存管理
风静如云7 小时前
VirtualBox:Win11下开启VT-x
windows
小镇学者7 小时前
【python】 macos 安装ffmpeg 命令行工具
python·macos·ffmpeg