代码随想录【字符串】

一刷: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
相关推荐
云天AI实战派2 分钟前
AI 智能体问题排查指南:ChatGPT、API 调用到 Agent 上线失灵的全流程修复手册
大数据·人工智能·python·chatgpt·aigc
我的xiaodoujiao39 分钟前
API 接口自动化测试详细图文教程学习系列15--项目实战演练2
python·学习·测试工具·pytest
Gary Studio1 小时前
安卓HAL C++基础-智能指针
开发语言·c++
啧不应该啊1 小时前
Day1 Python 与 C 的类型区别
c语言·开发语言
多思考少编码2 小时前
PAT甲级真题1001 - 1005题详细题解(C++)(个人题解)
c++·python·最短路·pat·算法竞赛
cen__y2 小时前
Linux07(信号01)
linux·运维·服务器·c语言·开发语言
ZhengEnCi2 小时前
M5-markconv自定义CSS样式指南 📝
前端·css·python
xingpanvip2 小时前
星盘接口开发文档:星相日历接口指南
android·开发语言·前端·css·php·lua
ZhengEnCi2 小时前
M4-更新日志v0.1.3-Mermaid图表支持 📝
python
guygg882 小时前
基于遗传算法的双层规划模型求解MATLAB实现
开发语言·matlab