剑指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. P1296 奶牛的耳语

    P1296 奶牛的耳语 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn) 本题核心思路: 1.读入后要排序以达到剪枝的目的 2.模拟,遇到不能再交流就转入下一头牛,否则计数器加一 3. ...

  2. CSS 常用样式-字体属性

    字体类样式我们已经学习过字号font-size.字体font-family两个属性,接下来还有几个常用的字体属性. 粗细 font-weight: 作用:设置文字是否加粗显示. 属性名:font-we ...

  3. 09 Hive安装与操作

    一.安装Hive 下载解压重命名权限 配置环境变量 修改Hive配置文件 修改/usr/local/hive/conf下的hive-site.xml 1 2 3 4 5 6 7 8 9 10 11 1 ...

  4. javaheima14

    Java 日志框架 日志框架的概述 记录程序运行过程中的信息,并可以进行永久存储 以前记录日志的方式--输出语句 弊端 信息只能展示在控制台 不能将其记录到其他位置(文件,数据库) 想取消记录的信息需 ...

  5. Java包机制与文档注释

    Java包机制与文档注释 包机制 为了更好地组织类,java提供包机制,用于区分类名的命名空间 包语句的语法: package pkg1.pkg2.pkg3...; // 必须在文件第一行 一般用公司 ...

  6. Okhttp请求

    theme: juejin highlight: a11y-dark 同步请求 OkHttpClient httpClient = new OkHttpClient(); String url = & ...

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

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

  8. form表单 css的选择器和一些属性以及盒子模型,浮动

    form表单 <form action='' method='' enctype=''> <input type='text'> input:更下type属性就可以得到对应的效 ...

  9. <a-upLoad>连报三错

    [Vue warn]: Invalid prop: custom validator check failed for prop "fileList". [Vue warn]: I ...

  10. eclipse微服务续,Hystrix+Gateway+Config配置管理中心+Bus动态刷新配置

    Hystrix延迟和容错库 Gateway微服务网关 Config配置管理中心 Bus动态刷新配置 四.Hystrix延迟和容错库 SpringCloud默认已为Feign整合了hystrix,所以添 ...