当前位置:网站首页>Leetcode 821. 字符的最短距离(简单) - 续集
Leetcode 821. 字符的最短距离(简单) - 续集
2022-06-27 17:57:00 【我是胖虎啊】
题目名称
821. 字符的最短距离
理解
个人觉得昨天的这个题很经典.大家可以此题为基础练习多种算法思想, 为以后学习算法打基础.参考其它大佬的解法, 整理了2个不错的思路, 方便大家参考.
中心扩展法
题目思路
- 每次遍历到一个变量时, 从该位置定义2个指针, 分别向左, 右遍历.计算2个位置到初始位置距离的最小值
- 将该最小值记录到数组中
code for Python3
class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
# 中心扩展法
len_s = len(s) - 1
arr = []
for i in range(len(s)):
shortest = float('inf')
if s[i] == c:
arr.append(0)
continue
else:
left, right = i, i
while left >= 0:
if s[left] == c:
shortest = min(shortest, i - left)
break
else:
left -= 1
while right <= len_s:
if s[right] == c:
shortest = min(shortest, right - i)
break
else:
right += 1
arr.append(shortest)
return arr
复杂度分析
- 时间复杂度: O(N²)
- 空间复杂度: O(1) 此处使用的是额外空间复杂度, 不考虑返回结果占用的空间!
滑动窗口法
题目思路
- 以预期字符串c为临界点, 划分为很多个窗口
- 遍历s中字符时, 分别计算当前字符与所在窗口左右边界点的距离,取最小值放到数组中
code for Python3
class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
# 滑动窗口法
arr = []
left = float('-inf')
right = s.find(c)
for i in range(len(s)):
if i == right:
# 更新窗口
left = right
right = s.find(c, right + 1)
if s[i] == c:
arr.append(0)
continue
else:
# 加了个判断, 如果right = -1,即最后一个窗口的右边界为字符串长度时, 此时的最小距离为当前字符与左边界的距离!
arr.append(min(i - left, right - i)) if right != -1 else arr.append(i - left)
return arr
- 时间复杂度: O(N) N为字符串S的长度
- 空间复杂度: O(1) 此处使用的是额外空间复杂度, 不考虑返回结果占用的空间!
python的相关知识
- 字符串中查找元素
# find()方法
s = "abcdefb"
print(s.find("b")) # 1
print(s.find("b", 2)) # 6 从指定位置后, 查询下一个字符串
print(s.find("k")) # -1
# index方法
s = "abcdefb"
print(s.index("b")) ## 1
print(s.index("b", 2)) # 6
print(s.index("k")) # ValueError: substring not found
可见, find 和 index 使用方法基本相同
相同点
1.都可以查找字符串中第一个出现的字符
2.都可以指定从某一个索引后面开始, 查找下一个出现的字符
不同点
1.find 找不到元素时,会返回-1
2.index 找不到元素时, 会返回 ValueError
- 列表中查找元素
s = ['a', 'b', 'c', 'd', 'e', 'f', 'b']
print(s.index("b"))
print(s.index("b", 2)) # 6
注意
1.list中查找元素,只能使用index, 无find方法.
2.查找不到元素时, 一样会出现 ValueError的异常边栏推荐
- 1023 Have Fun with Numbers
- 信息学奥赛一本通 1335:【例2-4】连通块
- redis集群系列二
- Market status and development prospect forecast of global 4-methyl-2-pentanone industry in 2022
- Online text batch inversion by line tool
- Market status and development prospect of resorcinol derivatives for skin products in the world in 2022
- Workflow automation low code is the key
- (LC)46. 全排列
- Where to look at high-yield bank financial products?
- Redis 原理 - String
猜你喜欢

Jinyuan's high-end IPO was terminated: it was planned to raise 750million Rushan assets and Liyang industrial investment were shareholders

Blink SQL built in functions

拥抱云原生:江苏移动订单中心实践

华大单片机KEIL报错_WEAK的解决方案

Minmei new energy rushes to Shenzhen Stock Exchange: the annual accounts receivable exceeds 600million and the proposed fund-raising is 450million

国际数字经济学院、华南理工 | Unified BERT for Few-shot Natural Language Understanding(用于小样本自然语言理解的统一BERT)

New Zhongda chongci scientific and Technological Innovation Board: annual revenue of 284million and proposed fund-raising of 557million

一种朴素的消失点计算方法

Erreur Keil de Huada Single Chip Computer La solution de Weak

数仓的字符截取三胞胎:substrb、substr、substring
随机推荐
Hanoi塔问题
RANSAC的代码和原理
Market status and development prospect forecast of global active quality control air sampler industry in 2022
binder hwbinder vndbinder
Bit.Store:熊市漫漫,稳定Staking产品或成主旋律
Cucumber自动化测试框架使用
1024 Palindromic Number
Jinyuan's high-end IPO was terminated: it was planned to raise 750million Rushan assets and Liyang industrial investment were shareholders
基于STM32F103ZET6库函数蜂鸣器实验
2022年第一季度消费金融APP用户洞察——总数达4479万人
金鱼哥RHCA回忆录:DO447管理项目和开展作业--创建作业模板并启动作业
Garbage collector driving everything -- G1
教你打印自己的日志 -- 如何自定义 log4j2 各组件
网络传输是怎么工作的 -- 详解 OSI 模型
拥抱云原生:江苏移动订单中心实践
The Fifth Discipline: the art and practice of learning organization
Tupu digital twin intelligent energy integrated management and control platform
Photoshop-图层相关概念-LayerComp-Layers-移动旋转复制图层-复合图层
一对一关系
过关斩将,擒“指针”(下)