当前位置:网站首页># Leetcode 821. Minimum distance of characters (simple)
# Leetcode 821. Minimum distance of characters (simple)
2022-06-27 20:43:00 【I am fat tiger】
Title
821. The shortest distance of a character
Think of your own solution
Topic ideas
- Traversal string s, Get expected character of record c stay s List of all locations in list_c
- Define a method : Get the input character and All the elements in the list The lowest absolute value of all the differences
- Traversal string s, Every time you traverse to a character , Call the custom method once , Record to array
code for Python3
class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
list_c = [i for i in range(len(s)) if s[i] == c]
arr = []
for j in range(len(s)):
arr.append(self.get_abs_minnum(j, list_c))
return arr
def get_abs_minnum(self, first_num:int, li:List):
cur = pow(10, 4)
for v in li:
cur = min(cur, abs(v - first_num))
return cur
Complexity analysis
- Time complexity : O(N²) reason : Double loop , Every time I traverse the string s when , It's all traversed once list_c
- Spatial complexity : O(N) reason : list_c The size of the space occupied and the string s The length of
Official explanation
I have studied the official solution carefully , I found that the idea was particularly ingenious , Its ideas are worth learning !
Topic ideas
- First traverse from left to right S, Record the current character and C Absolute value of distance . Before the expected value , This position is replaced by positive infinity ; After the expected value appears , Record the actual distance
- Traverse once from right to left S, alike Record the current character and C Absolute value of distance .
- In the 2 During the second traversal , Take the absolute value of the current traversal result And The first 1 Secondary traversal value The minimum value of , Add to array
code for Python3
class Solution(object):
def shortestToChar(self, S, C):
prev = float('-inf')
arr = []
for i, x in enumerate(S):
if S[i] == C:
prev = i
else:
arr.append(i - prev)
prev = float('inf')
for i in range(len(S) -1, -1, -1):
if S[i] == C:
prev = i
else:
arr.append(min(prev-i, arr[i]))
return arr
Complexity analysis
- Time complexity : O(N) reason : Only traversed 2 Substring S
- Spatial complexity : O(N) reason : arr Length of array
python Knowledge about
- enumerate Method : In the output data structure Indexes and value When you use
s = "abcdefg"
for i, j in enumerate(s):
print(i, j)
The result is :
0 a
1 b
2 c
3 d
4 e
5 f
6 g
--------------------------------------------------
for k in enumerate(s):
print(k)
The result is :
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
(4, 'e')
(5, 'f')
(6, 'g')
- About python Infinity in , An infinitesimal
Define infinity : float('inf')
Define infinitesimal : float('-inf')
A special case :
0* infinity or 0* An infinitesimal The result is nan( It's not a number , All and nan Can't get the result )
Other examples :
float('nan') + 9999999 # nan
float('nan') - 9999999 # nan
float('nan') * 9999999 # nan
0 - An infinitesimal -> infinity
0 - float('-inf') # float('inf')
- The reverse order output of the list
s = [1,2,3,4,5]
for i in range(len(s) - 1, -1, -1):
print(s[i])
The result is :
5
4
3
2
1边栏推荐
- UE4 actor Basics
- What is a low code development platform? Why is it so hot now?
- Implementation string mystring
- ABAP essays - interview memories hope that everyone's demand will not increase and the number of people will soar
- Linux system Oracle 19C OEM monitoring management
- UE4 essays: fstring, fname and ftext
- Common shell script commands (4)
- Enumeration and control flow operation in rust
- 低代码开发平台是什么?为什么现在那么火?
- 元宇宙虚拟数字人离我们更近了|华锐互动
猜你喜欢
随机推荐
微信iOS版8.0.24更新发布 缓存细分清理上线
[help] troubleshooting of JVM's high CPU resource consumption
I haven't thought about the source for some time. After upgrading to the latest version 24, the data encryption problem is repeatedly displayed
低代码开发平台是什么?为什么现在那么火?
数仓的字符截取三胞胎:substrb、substr、substring
Practice of combining rook CEPH and rainbow, a cloud native storage solution
How to reduce the weight transfer of unnecessary pages that users pay attention to?
Accumulating power in the middle stage, UFIDA IUAP builds a new base for digital intelligence of social enterprises
云原生安全指南: 从零开始学 Kubernetes 攻防
As a software engineer, give advice to young people (Part 2)
从指令交读掌握函数调用堆栈详细过程
数据库事务
数据库日志
MongoDB简介及典型应用场景
Batch insert data using MySQL bulkloader
Recommended practice sharing of Zhilian recruitment based on Nebula graph
一段时间没用思源,升级到最新的 24 版后反复显示数据加密问题
回溯相关问题
Mass lucky hash game system development - conflict resolution (code analysis)
优维HyperInsight:掘金164.94亿美元可观测市场的“金锄头”?









