剑指Offer 05: 替换空格

题目描述

请实现一个函数,把字符串 s 中的每个空格替换成"%20"

建立模型

  1. 这就是一个遍历字符串元素替换的问题
  2. 需要注意的就是Python/Java中的str是不可变类型,需要转化成可变类型的List/StringBuilder拼接

代码实现

# Python3 实现
def replaceSpace(self, s: str) -> str:
res = []
for ch in s:
if ch == ' ':
res.append('%20')
else:
res.append(ch)
return ''.join(res)
// Java 实现
public String replaceSpace(String s) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == " ") {
sb.append("%20");
}
else {
sb.append(c);
}
} return sb.toString();
}

LeeCode 28: 实现strStr()

题目描述

给你两个字符串 haystackneedle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回  -1

建立模型

暴力匹配

  1. 让字符串 needle 与 haystack 所有长度相等的子串匹配一次
  2. 时间复杂度 O(M * N),M为needle字符串长度,N为haystack字符串长度

KMP算法

来自我的另一篇文章KMP字符串匹配

代码实现

# Python3 暴力匹配
def strStr(self, haystack: str, needle: str) -> int:
if needle is None or needle == ' ':
return 0
i, j = 0, len(needle)
while j <= len(haystack):
if haystack[i:j] == needle:
return i
i += 1
j += 1 return -1
// Java 暴力匹配
public int strStr(String haystack, String needle) {
if (needle == null || needle.length() == 0) {
return 0;
} int i = 0, j = needle.length();
while (j <= haystack.length()) {
if (haystack.substring(i, j).equals(needle)) {
return i;
}
i += 1;
j += 1;
} return -1;
}

LeeCode 459: 重复的子字符串

题目描述

给定一个非空的字符串 s ,检查是否可以通过由它的一个子串重复多次构成。

建立模型

暴力求解

  1. 枚举子串的长度 {1 ~ \(\frac{len(s)}{2}\)},最少需要重复两次

  2. 如果字符串s满足由一个子串重复多次构成,假设子串长度为m,则有如下关系:

    \[s[i] == s[i - m] \quad \forall i \ge m
    \]

巧妙解法

  1. 如果字符s满足由一个子串重复多次构成,则 \(s = n * s_1\)
  2. 将字符串拷贝一份得到\(s^{'} = 2*s = 2*n*s_1\)
  3. 破坏首尾两个\(s_1\),中间还存在 \(2*n - 2 \ge n (n \ge 2)\)
  4. 所以原字符串s应该是\(s^{'}\)的子串

代码实现

# Python3 暴力求解
def repeatedSubstringPattern(self, s: str) -> bool:
# 枚举子串长度
for i in range(1, len(s) // 2 + 1):
if len(s) % i == 0:
flag = True
for j in range(i, len(s)):
if s[j] != s[j - i]:
flag = False
break
if flag:
return True
return False # Python3 巧妙求解
def repeatedSubstringPattern(self, s: str) -> bool:
# 分别去除首尾单个字符破坏子串
return s in (s + s)[1:-1]
// Java 暴力求解
boolean repeatedSubstringPattern(String str) {
for (int i = 1; i < str.length() / 2 + 1; i++) {
if (str.length() % i == 0) {
boolean flag = true;
for (int j = i; j < str.length(); j++) {
if (str.charAt(j) != s.charAt(j - i)) {
flag = false;
break;
}
}
if (flag) {
return true;
}
}
} return false;
} // Java 巧妙解法
boolean repeatedSubstringPattern(String str) {
String s = str.concat(str).substring(1, 2*str.length() - 1);
if (s.index(str) != -1) {
return true;
} return false;
}

LeeCode 字符串问题(一)的更多相关文章

  1. leecode刷题(16)-- 字符串转换整数

    leecode刷题(16)-- 字符串转换整数 字符串转换整数 描述: 请你来实现一个 atoi 函数,使其能将字符串转换成整数. 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格 ...

  2. leecode刷题(15)-- 验证回文字符串

    leecode刷题(15)-- 验证回文字符串 验证回文字符串 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写. 说明:本题中,我们将空字符串定义为有效的回文串. 示例 ...

  3. leecode刷题(13) -- 字符串中的第一个唯一字符

    leecode刷题(13) -- 字符串中的第一个唯一字符 字符串中的第一个唯一字符 描述: 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引.如果不存在,则返回 -1. 案例: s = & ...

  4. leecode刷题(11)-- 反转字符串

    leecode刷题(11)-- 反转字符串 反转字符串 描述: 编写一个函数,其作用是将输入的字符串反转过来. 示例 1: 输入: "hello" 输出: "olleh& ...

  5. leecode第五百五十七题(反转字符串中的单词 III)

    class Solution { public: string reverseWords(string s) { string res; stack<char> sta; string:: ...

  6. Leecode刷题之旅-C语言/python-434 字符串中的单词数

    /* * @lc app=leetcode.cn id=434 lang=c * * [434] 字符串中的单词数 * * https://leetcode-cn.com/problems/numbe ...

  7. Leecode刷题之旅-C语言/python-387 字符串中的第一个唯一字符

    /* * @lc app=leetcode.cn id=387 lang=c * * [387] 字符串中的第一个唯一字符 * * https://leetcode-cn.com/problems/f ...

  8. Leecode刷题之旅-C语言/python-344反转字符串

    /* * @lc app=leetcode.cn id=344 lang=c * * [344] 反转字符串 * * https://leetcode-cn.com/problems/reverse- ...

  9. leecode 回文字符串加强版

    Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignori ...

  10. leecode第三百四十四题(反转字符串)

    class Solution { public: void reverseString(vector<char>& s) { int len=s.size(); char temp ...

随机推荐

  1. 【Unity】检测目标是否在视线范围内(附视线范围扇形画法)

    检测目标是否在视线范围内(附视线范围扇形画法) using UnityEngine; public class Test_CanSeeTarget : MonoBehaviour { public G ...

  2. sql年、季度、月的第一天

    SELECT dateadd(yy,datediff(yy,0,getdate()),0) select dateadd(qq,datediff(qq,0,getdate()),0) select d ...

  3. 循环文件夹汇总所有下载发票的Excel文件数据

    Dim a As String, n As Integer, wbs As Workbook ThisWorkbook.Sheets(1).Cells.Clear a = Dir(ThisWorkbo ...

  4. bat将多个文件夹下内容合并到一个文件夹下

    for /f "delims=" %%p in ('dir /b/ad') do copy %%p\*.* d:\all\ pause 目标文件夹 d:\all\ 最好不用中文目录

  5. [Lua]敏感字检测

    参考链接: https://zhuanlan.zhihu.com/p/84685657 https://www.cnblogs.com/luguoshuai/p/9254190.html 一开始打算使 ...

  6. 使用Jmeter进行https接口测试时,如何导入证书?

    转载:https://www.cnblogs.com/tester-zhangxiaona/p/12295473.html

  7. java.lang.StackOverflowError错误的解决方法

    对于java.lang.StackOverflowError认识 如下图所示,报出来这种错误的话,很大概率是有以下几种原因: 现在来看一看我的报错界面: 不难看出,这是无限循环的那种情况,所以,我就去 ...

  8. Nacos与OpenFeign开发

    目录 1.前言 2.生产者 3.消费者 4.扩展 1.前言 我的话是微服务B调用微服务A的controller层 2.生产者 微服务A请求接口如下: @GetMapping("/listUn ...

  9. AD域安全攻防实践(附攻防矩阵图)

    以域控为基础架构,通过域控实现对用户和计算机资源的统一管理,带来便利的同时也成为了最受攻击者重点攻击的集权系统. 01.攻击篇 针对域控的攻击技术,在Windows通用攻击技术的基础上自成一套技术体系 ...

  10. # 1. C++概述

    1. C++概述 1.1 c++简介 "c++"中的++来自于c语言中的递增运算符++,该运算符将变量加1.c++起初也叫"c with clsss".通过名称 ...