字符串章节 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
相关推荐
biter down17 小时前
9:JSONSchema
python
风筝在晴天搁浅17 小时前
快手 CodeTop LeetCode 224.基本计算器
数据结构·算法·leetcode
Smoothcloud润云17 小时前
5大功能精修,重构AI算力使用体验!
java·人工智能·windows·算法·重构·编辑器·sublime text
日晨难再17 小时前
C语言&Python&Bash&Tcl:全局变量和局部变量
c语言·python·bash·tcl
麻雀飞吧17 小时前
期货量化主连和具体合约怎么切:天勤 KQ.m 与 KQ.i 用法
python·区块链
先吃饱再说17 小时前
Python List 切片与 LLM Prompt 设计:从数据结构到接口调用
python
ModestCoder_17 小时前
windows/ubuntu解决挂梯子但是codex reconnecting五次的问题
linux·windows·ubuntu
一只专注api接口开发的技术猿18 小时前
OpenClaw 对接淘宝商品 API,低成本实现全天候选品监控|附可运行 Python 实操代码
大数据·开发语言·数据库·python
xingpanvip18 小时前
星盘接口开发文档:马盘次限盘接口指南
android·开发语言·python·php·lua
FBI HackerHarry浩18 小时前
第二阶段Day07【Python生成器、yield关键字、property、正则表达式】
开发语言·python·正则表达式