字符串章节 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
相关推荐
2501_9419820519 小时前
企业微信二次开发:私域数据基石——三大核心基础能力接口实战
windows·架构·bootstrap·企业微信
闻道且行之21 小时前
TurboOCR:基于PP-OCRv6的极速Windows离线OCR工具,深度解析3.4GB依赖背后的技术架构
c++·人工智能·python·qt·机器学习·ocr
许彰午1 天前
95_Python内存管理与垃圾回收
开发语言·python
骄阳如火1 天前
Python 性能深度剖析:从“被诟病的慢”到“Rust 重塑”的拐点
python
满怀冰雪1 天前
03-第一个 Paddle 程序:Tensor 创建、计算与设备管理
人工智能·python·paddle
CClaris1 天前
大模型量化从0到1(九):用 llama.cpp 把模型转成 GGUF 并跑本地推理
人工智能·pytorch·python·深度学习·llama
学编程的小虎1 天前
SenseVoice微调
人工智能·python·自然语言处理
诸葛说抛光1 天前
国内大型汽车改装展览会定展 佛山改装 佛山汽车赛事
python·汽车
chouchuang1 天前
day-030-综合练习-笔记管理器
开发语言·笔记·python
乖巧的妹子1 天前
Python基础核心知识点详解:内置函数、运算符、字符串方法、数据结构与类型转换
python