剑指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. setter注入--简单类型

    UserDaoImpl中的代码,实现对name和age的注入 private String name; private int age; public void setName(String name ...

  2. 图模配置文件之 flow.json

    flow.json文件是用来配置图模导入时,各种不同的图模导入时,分别应该使用哪个映射文件对模型进行处理.在不同地区使用不同的格式的图模文件时,需要修改flow.json中相关的配置,来适应相应的图模 ...

  3. Lombok和MapStruct冲突

    Lombok和MapStruct冲突导致无法生成正确的class文件. lombok自动生成getset等冗余代码. MapStruct对象copy.传统的BeanUtils.copy等利用的反射原理 ...

  4. (六).JavaScript的数组(2)

    1.10 作用域链 定义: 作用域链:查找变量的过程 作用: 查找变量 查找规则:首先会在自身作用域找变量,找到就用 如果没有,就去上级作用域查找,找到就用 如果没有,一直往上找,直到全局作用域,有就 ...

  5. 【随笔】记录Centos7 firewall-cmd防火墙的文档与命令记录

    注意:firewall-cmd命令后面的参数前面是两个短-,这里显示的不是很清晰 查看firewall-cmd运行状态 # firewall-cmd --state 开放8080端口 # firewa ...

  6. C# winform DataGridView 一列显示星号

    private void myDataGrid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventA ...

  7. 解决ssh $host jps bash: jps: command not found 问题

    问题描述 使用 ssh $host jps 命令报错,连本机也会有这样的情况,但是分开使用并没有问题,即ssh $host下执行jps命令并不会报错. 原因 因为ssh远程连接到服务器的环境变量中不包 ...

  8. element表格样式修改

    HTML代码: <el-table :data="tableData" style="width: 100%" border :row-class-nam ...

  9. Keil Jlink没法找到STM32H750

    https://www.amobbs.com/thread-5713382-1-1.html MDK使用的是5.32,jlink使用的是9.2jlink驱动使用的是6.44b 删除工程下的JLinkS ...

  10. windows下配置JDK教程

    1.思路: 首先要确定所要用的应用可以兼容哪个版本jdk,然后开始下载对应的版本,最后安装,配置环境变量,测试,部署完成. 2.jdk下载地址: 如果下载全新的jdk可以直接百度jdk官网下载 如果需 ...