@@ -15,11 +15,11 @@ https://leetcode-cn.com/problems/shortest-distance-to-a-character/
1515 - [ 解法 3:贪心] ( #解法-3贪心 )
1616 - [ 思路] ( #思路-2 )
1717 - [ 复杂度分析] ( #复杂度分析-2 )
18- - [ 代码 (JS/C++)] ( #代码-jsc-2 )
18+ - [ 代码 (JS/C++/Python )] ( #代码-jscpython )
1919 - [ 解法 4:窗口] ( #解法-4窗口 )
2020 - [ 思路] ( #思路-3 )
2121 - [ 复杂度分析] ( #复杂度分析-3 )
22- - [ 代码 (JS/C++)] ( #代码-jsc-3 )
22+ - [ 代码 (JS/C++/Python )] ( #代码-jscpython-1 )
2323
2424## 题目描述
2525
@@ -258,7 +258,7 @@ public:
258258- 时间复杂度:$O(N)$,N 是 S 的长度。
259259- 空间复杂度:$O(1)$。
260260
261- ### 代码 (JS/C++)
261+ ### 代码 (JS/C++/Python )
262262
263263JavaScript Code
264264
@@ -347,6 +347,29 @@ public:
347347};
348348```
349349
350+ Python Code
351+
352+ ``` py
353+ class Solution (object ):
354+ def shortestToChar (self , s , c ):
355+ """
356+ :type s: str
357+ :type c: str
358+ :rtype: List[int]
359+ """
360+ n = len (s)
361+ res = [0 if s[i] == c else None for i in range (n)]
362+
363+ for i in range (1 , n):
364+ if res[i] != 0 and res[i - 1 ] is not None :
365+ res[i] = res[i - 1 ] + 1
366+
367+ for i in range (n - 2 , - 1 , - 1 ):
368+ if res[i] is None or res[i + 1 ] + 1 < res[i]:
369+ res[i] = res[i + 1 ] + 1
370+ return res
371+ ```
372+
350373## 解法 4:窗口
351374
352375### 思路
@@ -360,7 +383,7 @@ public:
360383- 时间复杂度:$O(N)$,N 是 S 的长度。
361384- 空间复杂度:$O(1)$。
362385
363- ### 代码 (JS/C++)
386+ ### 代码 (JS/C++/Python )
364387
365388JavaScript Code
366389
@@ -419,4 +442,28 @@ public:
419442};
420443```
421444
445+ Python Code
446+
447+ ``` py
448+ class Solution (object ):
449+ def shortestToChar (self , s , c ):
450+ """
451+ :type s: str
452+ :type c: str
453+ :rtype: List[int]
454+ """
455+ n = len (s)
456+ res = [0 for _ in range (n)]
457+
458+ l = 0 if s[0 ] == c else n
459+ r = s.find(c, 1 )
460+
461+ for i in range (n):
462+ res[i] = min (abs (i - l), abs (r - i))
463+ if i == r:
464+ l = r
465+ r = s.find(c, l + 1 )
466+ return res
467+ ```
468+
422469更多题解可以访问:[ https://github.com/suukii/91-days-algorithm ] ( https://github.com/suukii/91-days-algorithm )
0 commit comments