字符串章节 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
相关推荐
半城抹茶16 分钟前
TradingAgents-CN 项目目录文档
python
光影62719 分钟前
Selenium自动化测试---实战踩坑实录
python·selenium·测试工具·百度
HappyAcmen31 分钟前
2.lcut返回列表用法
python
Json____35 分钟前
Python练习题集-文件处理、数据管理与网络编程实战小项目15个
python·编程·编程学习·练习题·python学习
星空椰41 分钟前
Python 使用飞书 API 获取部门直属用户列表(递归获取所有部门 + 导出 Excel)
python·飞书
l1t1 小时前
在aarch64机器上安装clang来生成codonjit python模块
开发语言·python
辰尘_星启1 小时前
【Linux】Python Socket编程指南
linux·python·socket·系统·通信
南宫萧幕1 小时前
基于 Simulink 与 Python 联合仿真的 eVTOL 强化学习全链路实战
开发语言·人工智能·python·算法·机器学习·控制
Amctwd1 小时前
【Python】从Excel中按行提取图片
java·python·excel
张二娃同学2 小时前
第08篇_RNN_LSTM_GRU序列模型
人工智能·python·rnn·深度学习·神经网络·gru·lstm