当前位置:网站首页># 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边栏推荐
- I haven't thought about the source for some time. After upgrading to the latest version 24, the data encryption problem is repeatedly displayed
- Linux system plays Oracle database multi table query connection query with a smile
- As a software engineer, give advice to young people (Part 2)
- Web APLS phase - Section 14 - local storage
- UE4 essays: fstring, fname and ftext
- Installing services for NFS
- Longitude and latitude analysis
- [help] troubleshooting of JVM's high CPU resource consumption
- Logcli-loki 命令行工具
- Pfsense plus22.01 Chinese customized version release
猜你喜欢

Recommended practice sharing of Zhilian recruitment based on Nebula graph

花了6个月时间完成本科优秀毕业设计,我做了什么?

Redis cluster

Database transactions

Massive data attended the Lanzhou opengauss meetup (ECOLOGICAL NATIONAL trip) activity, enabling users to upgrade their applications with enterprise level databases

谈谈我写作生涯的画图技巧
Record a failure caused by a custom redis distributed lock

Runmaide medical opened the offering: without the participation of cornerstone investors, the amount of loss doubled

Connection integration development theme month | drivers of enterprise master data governance

BAIC makes a brand new pickup truck, which is safe and comfortable
随机推荐
Cocoscreator plays audio and synchronizes progress
At 19:00 on Tuesday evening, the 8th live broadcast of battle code Pioneer - how to participate in openharmony's open source contribution in multiple directions
Postman 汉化教程(Postman中文版)
【STL编程】【竞赛常用】【part 2】
ABAP essay - get new crown data through API
CSDN skill tree experience and product analysis (1)
Record a failure caused by a custom redis distributed lock
Type the URL to the web page display. What happened during this period?
键入网址到网页显示,期间发生了什么?
Openharmony hisysevent dotting and calling practice of # Summer Challenge (L2)
Database index
Connection integration development theme month | drivers of enterprise master data governance
Bit. Store: long bear market, stable stacking products may become the main theme
数据库事务
【STL编程】【竞赛常用】【part 3】
At 19:00 on Tuesday evening, the 8th live broadcast of battle code Pioneer - how to participate in openharmony's open source contribution in multiple directions
ABAP-CL_ OBJECT_ Collection tool class
Enumeration and control flow operation in rust
DBeaver恢复和备份数据库的方式
MongoDB简介及典型应用场景