代码随想录【字符串】

一刷:6月3日到6月9日

反转字符串

python 复制代码
 		l=0
        r=len(s)-1
        while l<r:
            s[l],s[r]=s[r],s[l]
            l+=1
            r-=1

反转字符串II

python 复制代码
        res=list(s)
        for i in range(0,len(s),2*k):
            res[i:i+k]=res[i:i+k][::-1]
        
        return "".join(res)

替换数字

没有使用额外的空间

python 复制代码
s=list(input())
l=len(s)-1
x=['r','e','b','m','u','n']
num=0
for i in s:
    if i.isdigit():
        num+=1
for i in range(num*5):
    s.append(0)
idx_2=len(s)-1
for idx_1 in range(l,-1,-1):
    if s[idx_1].isdigit():
        for sx in x:
            s[idx_2]=sx
            idx_2-=1
    else:
        s[idx_2]=s[idx_1]
        idx_2-=1

print("".join(s))

翻转字符串里的单词

python 复制代码
 		s.strip()
        s=s[::-1]
        return " ".join([x[::-1] for x in s.split()])

右旋转字符串

这么写超时了。。。

python 复制代码
k=int(input())
s=list(input())
for i in range(k):
    x=s[-1]
    for i in range(len(s)-1,0,-1):
        s[i]=s[i-1]
    s[0]=x
print("".join(s))

这个跟上一题翻转字符串里的单词有异曲同工之妙

python 复制代码
k=int(input())
s=list(input())
s=s[::-1]
s[0:k]=s[0:k][::-1]
s[k:]=s[k:][::-1]
print("".join(s))

实现strStr(())

KMP算法的实现

i是后缀末尾

j是前缀末尾

python 复制代码
def getnext(self,s,next):
        
        j=0
        next[0]=0
        for i in range(1,len(s)):
            while j>0 and s[j]!=s[i]:
                j=next[j-1]
            if s[i]==s[j]:
                j+=1
            next[i]=j
        return next
        
    def strStr(self, haystack, needle):
        next=[0]*len(needle)
        self.getnext(needle,next)
        j=0
        for i in range(len(haystack)):
            while j>0 and haystack[i]!=needle[j]:
                j=next[j-1]
            if haystack[i]==needle[j]:
                j+=1
            if j==len(needle):
                return i-len(needle)+1
        return -1

重复的子字符串

python 复制代码
 def getnext(self,s):
        next=[0]*len(s)
        j=0
        next[0]=0
        for i in range(1,len(s)):
            while j>0 and s[j]!=s[i]:
                j=next[j-1]
            if s[i]==s[j]:
                j+=1
            next[i]=j
        return next[-1]  #返回最大相等公共子字符串的最大数

    def repeatedSubstringPattern(self, s):
       
        num=self.getnext(s)
        if len(s)%(len(s)-num)==0 and num!=0: #有可能返回为0,如"abac"
            return True
        else:
            return False
相关推荐
IVEN_16 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang17 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮17 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling17 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮20 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽21 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞2 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽2 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers