当前位置:网站首页># 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边栏推荐
- 【STL编程】【竞赛常用】【part 1】
- BLE蓝牙模块NRF518/NRF281/NRF528/NRF284芯片方案对比
- 灵活的IP网络测试工具——— X-Launch
- Character interception triplets of data warehouse: substrb, substr, substring
- Database optimization
- BAIC makes a brand new pickup truck, which is safe and comfortable
- Pfsense plus22.01 Chinese customized version release
- Record a failure caused by a custom redis distributed lock
- Redis data structure
- 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
猜你喜欢

redis数据结构

Database lock problem

Practice of combining rook CEPH and rainbow, a cloud native storage solution

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

Wechat IOS version 8.0.24 update release cache subdivision cleaning Online

【STL编程】【竞赛常用】【part 3】

It took me 6 months to complete the excellent graduation project of undergraduate course. What have I done?

Linux系统ORACLE 19C OEM监控管理

Type the URL to the web page display. What happened during this period?

本周二晚19:00战码先锋第8期直播丨如何多方位参与OpenHarmony开源贡献
随机推荐
SQL报了一个不常见的错误,让新来的实习生懵了
低代码开发平台是什么?为什么现在那么火?
Dictionary tree (review)
No wonder people chose apifox instead of postman
#yyds干货盘点#SQL 子查询
NVIDIA三件套环境配置
Backtracking related issues
[数组]BM99 顺时针旋转矩阵-简单
Enumeration and control flow operation in rust
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
使用MySqlBulkLoader批量插入数据
How dbeaver restores and backs up databases
ABAP essay - get new crown data through API
云原生安全指南: 从零开始学 Kubernetes 攻防
探秘GaussDB,听听客户和伙伴怎么说
Univision hyperinsight: Nuggets' $16.494 billion "gold hoe" in the observable market?
Implementation string mystring
Accumulating power in the middle stage, UFIDA IUAP builds a new base for digital intelligence of social enterprises
一段时间没用思源,升级到最新的 24 版后反复显示数据加密问题
Mass lucky hash game system development - conflict resolution (code analysis)