字符串章节 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
相关推荐
aqi004 小时前
15天学会AI应用开发(九)利用Chroma持久化向量数据
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵4 小时前
借助 Pygame 探索最大公约数的规律
python·数学·游戏
To_OC16 小时前
LC 128 最长连续序列:别上来就排序,O (n) 解法才是这题的灵魂
javascript·算法·leetcode
ServBay21 小时前
9 个 Python 第三方库推荐,不用 AI 都好像多出一个团队
后端·python
用户83562907805121 小时前
如何使用 Python 添加和管理 Excel 批注(完整示例)
后端·python
用户83562907805121 小时前
使用 Python 管理 Excel 工作表:创建、复制、删除与重命名
后端·python
荣码1 天前
LangGraph多Agent协作:3个Agent干活比1个强,但我踩了4个坑
java·python
用户8356290780512 天前
Python 操作 PDF 附件:添加、查看与管理指南
后端·python
宇宙之一粟2 天前
乐企版式文件生成平台
java·后端·python