剑指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. python3GUI--在线小说播放器By:PyQt5(附ui源码)

    目录 一.准备工作 1.PyQt5 2.qtawesome 3.QMediaPlayer 4.LAVFilters 二.预览 1.启动 2.查看小说详情&播放小说 3.搜索后播放 4.动态演示 ...

  2. Linux系统管理实战-DNS

    DNS 域名解析 DNS(domain name system) 解析方式 1.本地解析 /etc/hosts 127.0.0.1 localhost localhost.localdomain lo ...

  3. 3html5

    <label>网址:</label><input type="url" name="" required><br> ...

  4. SDC细节归纳

    能否写出一份严谨的SDC约束文件,决定了芯片tapeout后数字电路能否正常工作,或者少一些bug.所以写好SDC约束文件,是芯片设计的关键一步. 因此,归纳.整理SDC约束的细节要点很重要,有助于减 ...

  5. CVE-2016-2183(SSL/TLS)漏洞的办法

    运行gpedit.msc,打开"本地组策略编辑器" 启用"SSL密码套件顺序" TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_ ...

  6. [.Net]Framwork WebAPI添加接口请求监控

    思路: 通过重写 ActionFilterAttribute 拦截Action的请求及返回信息,实现对接口请求的监听. 最终效果如下: 全局启用需配置如下: 局部启用需配置如下: 源码如下: 1 // ...

  7. String当中的intern()

    public class String001 { public static void main(String[] args) { String s1 = "hello"; Str ...

  8. 在服务器建立git服务端接收push后覆盖部署记录

    1.在本地要部署的目录 git initgit clone --bare ./ my_project.git 把本地init仓库克隆到 my_project.git 2.上传my_project.gi ...

  9. LeetCode86 分隔链表

    idea: 烦死了,这个题一直因为创立的指针为空,或者接入结点方法不对,结果将两个小链表搞混乱了,不过具体思路ok.将小值结点成一组,大值结点成一组,最后在首尾相连,实现起来也比较简单 /**  *  ...

  10. Springboot ehcache/redis双缓存问题

    问题1:两个CacheManager 会报两个相同的实现类错误需要继承CachingConfigurerSupport 重写cacheManager方法,指定默认一个返回缓存提供者 @Configur ...