LeetCode 821.字符的最短距离(python)
2019-03-23 16:31
766 查看
题目描述:
给定一个字符串 S 和一个字符 C。返回一个代表字符串 S 中每个字符到字符串 S 中的字符 C 的最短距离的数组。
示例 1:
输入: S = “loveleetcode”, C = ‘e’
输出: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
说明:
字符串 S 的长度范围为 [1, 10000]。
C 是一个单字符,且保证是字符串 S 里的字符。
S 和 C 中的所有字母均为小写字母。
解题思路:
先将字符串中C表示的字符的位置记录下来,然后计算字符串中每一个字符与所有字符C的距离,并求出最小距离即可。
p.s.别人的做法,用i表示当前字符,s[i:].find(c)表示右边的最近距离,s[i-len(s)::-1].find(c)表示左边的最近距离,取两者最小值,若当前字符左边或右边没有字符C,会返回-1,将-1设为一个较大的数即可。
class Solution: def shortestToChar(self, S: str, C: str) -> List[int]: loc=[] dis=[] for i in range(0,len(S)): if S[i]==C: loc.append(i)#记录e在列表中的位置 for i in range(0,len(S)): t=[] for j in loc: t.append(abs(i-j))#计算每一个字符和所有C的距离 dis.append(min(t))#将最小距离添加到结果数组中 return dis
相关文章推荐
- leetcode 821字符的最短距离
- LeetCode 821 字符的最短距离
- leetcode - 821 - 字符的最短距离
- Leetcode刷题32-821.字符的最短距离(C++)
- [LeetCode] 244. Shortest Word Distance II 最短单词距离 II
- [leetcode 244] Shortest Word Distance II------------字典中两个字符串的最短距离
- [LeetCode] Shortest Word Distance 最短单词距离
- leetcode之3. 无重复字符的最长子串python实现
- LeetCode3. 无重复字符的最长子串(python)
- 【leetcode】(Python)Reverse Vowels of a String实现字符串内元字符倒序
- LeetCode 3. 无重复字符的最长子串 Python
- [LeetCode]Word Ladder 最短距离字符串转换 (Dijkstra)
- LeetCode题解(python)-3.无重复字符的最长子串
- LeetCode 243. Shortest Word Distance (最短单词距离)$
- LeetCode 849. 到最近的人的最大距离 Python
- Python实现求两个字符串的最短编辑距离
- LeetCode-Python-849. 到最近的人的最大距离
- LeetCode 317. Shortest Distance from All Buildings(最短建筑距离)
- LeetCode题解(python)-1002. 查找常用字符
- 【LeetCode】Python实现-581. 最短无序连续子数组