当前位置:网站首页>Leetcode 821. Minimum distance of characters (simple) - sequel
Leetcode 821. Minimum distance of characters (simple) - sequel
2022-06-27 20:43:00 【I am fat tiger】
Title
821. The shortest distance of a character
understand
Personally, I think yesterday's question is very classic . You can practice a variety of algorithmic ideas on this topic , Lay the foundation for future learning algorithms . Refer to the solutions of other big men , Tidy up 2 A good idea , For your reference .
The central expansion method
Topic ideas
- Each time you traverse a variable , Defined from this location 2 A pointer to the , To the left , Right traversal . Calculation 2 The minimum value of the distance from the first position to the initial position
- Record the minimum value in the array
code for Python3
class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
# The central expansion method
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
Complexity analysis
- Time complexity : O(N²)
- Spatial complexity : O(1) The extra space complexity used here , Regardless of the space occupied by the returned results !
Sliding window method
Topic ideas
- With expected string c Is the critical point , Divided into many windows
- Traverse s Chinese characters , Calculate the distance between the current character and the left and right boundary points of the window , Take the minimum value and put it in the array
code for Python3
class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
# Sliding window method
arr = []
left = float('-inf')
right = s.find(c)
for i in range(len(s)):
if i == right:
# Update window
left = right
right = s.find(c, right + 1)
if s[i] == c:
arr.append(0)
continue
else:
# Add a judgment , If right = -1, That is, when the right boundary of the last window is the string length , At this time, the minimum distance is the distance between the current character and the left boundary !
arr.append(min(i - left, right - i)) if right != -1 else arr.append(i - left)
return arr
- Time complexity : O(N) N For the string S The length of
- Spatial complexity : O(1) The extra space complexity used here , Regardless of the space occupied by the returned results !
python Knowledge about
- Find element in string
# find() Method
s = "abcdefb"
print(s.find("b")) # 1
print(s.find("b", 2)) # 6 From the specified position , Query the next string
print(s.find("k")) # -1
# index Method
s = "abcdefb"
print(s.index("b")) ## 1
print(s.index("b", 2)) # 6
print(s.index("k")) # ValueError: substring not found
so , find and index The usage is basically the same
The same thing
1. Can find the first character in the string
2. You can specify to start after an index , Find the next character to appear
Difference
1.find When the element cannot be found , Returns the -1
2.index When the element cannot be found , Returns the ValueError
- Look for elements in the list
s = ['a', 'b', 'c', 'd', 'e', 'f', 'b']
print(s.index("b"))
print(s.index("b", 2)) # 6
Be careful
1.list Search for elements , Only use index, nothing find Method .
2. When the element cannot be found , The same will happen ValueError It's abnormal
边栏推荐
- Web APLS phase - Section 14 - local storage
- [array]bm99 clockwise rotation matrix - simple
- DBeaver恢复和备份数据库的方式
- Linux system plays Oracle database multi table query connection query with a smile
- Eval function, global, local variables
- 数据库索引
- BLE蓝牙模块NRF518/NRF281/NRF528/NRF284芯片方案对比
- Implementation string mystring
- Enumeration and control flow operation in rust
- 键入网址到网页显示,期间发生了什么?
猜你喜欢
Graylog 新一代日志收集预警系统安装配置
Redis persistence
[STL programming] [common competition] [Part 2]
谈谈我写作生涯的画图技巧
云原生存储解决方案Rook-Ceph与Rainbond结合的实践
润迈德医疗开启招股:未有基石投资者参与,亏损金额翻倍增长
MongoDB简介及典型应用场景
Accumulating power in the middle stage, UFIDA IUAP builds a new base for digital intelligence of social enterprises
Select auto increment or sequence for primary key selection?
北汽制造全新皮卡曝光,安全、舒适一个不落
随机推荐
Data intelligence enters the "deep water area", and data governance is the key
数据库优化
Database optimization
Database lock problem
CSDN skill tree experience and product analysis (1)
MongoDB简介及典型应用场景
SQL reported an unusual error, which confused the new interns
智联招聘的基于 Nebula Graph 的推荐实践分享
一场分销裂变活动,不止是发发朋友圈这么简单
Backtracking related issues
No wonder people chose apifox instead of postman
Pycharm common functions - breakpoint debugging
UE4 essays: fstring, fname and ftext
Oracle 架构汇总
本周二晚19:00战码先锋第8期直播丨如何多方位参与OpenHarmony开源贡献
数据仓库体系之贴源层、历史层
【STL编程】【竞赛常用】【part 1】
Web APls 阶段——第十四节——本地存储
Redis cluster
Logcli Loki command line tool