Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string.
Example 1:
Input: S = “loveleetcode”, C = ‘e’
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
Note:
S string length is in [1, 10000].
C is a single character, and guaranteed to be in string S.
All letters in S and C are lowercase.
分析:
找S中所有元素距离给定C的最小距离,注意数据长度10000,说明n^2不行
思路:
先将S中所有的C的位置找出来,然后以这些位置两两为一段,对这一段中的元素判断离那边端点更近就OK,-1处和len(s)处默认有一个,这两个边界问题注意处理
1 | def shortestToChar(S, C): |