代码随想录【字符串】

一刷: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
相关推荐
飞Link13 小时前
什么是 AirSim?一文读懂无人机仿真平台
python·算法·无人机
学逆向的13 小时前
C 堆区内存管理
c语言·开发语言·网络安全
huoyueyi13 小时前
《融天AI-APP从0到1开发实录》
开发语言·lua
曲径海盗13 小时前
【Python 学习第 38 天】for 循环
python·学习笔记·编程入门
在世修行14 小时前
智学文枢:变式题生成引擎
python·ai·pyside·题目生成
OpenAnolis小助手15 小时前
PHP 两个严重漏洞曝光,龙蜥社区 24 小时完成 3 版本修复
开发语言·操作系统·php·龙蜥社区
On The Road :16 小时前
Java 多线程详解:从入门到线程安全
java·python·安全
阿尼卡~16 小时前
VS Code 配置 C 语言开发环境(Windows 10/11):从 GCC 安装到运行、断点调试,一篇搞定
c语言·开发语言·windows
岁月宁静16 小时前
如何设计支持 Skills 的 Agent?一套可扩展的四层架构
python·agent
岁月宁静16 小时前
CrewAI 快速上手:10 分钟搭建你的第一个 Agent 团队
python·agent