# 821. Shortest Distance to a Character

**<font color=red>难度: Easy</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/shortest-distance-to-a-character/

> 内容描述

```
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.
```

## 解题方案

> 思路 1
******- 时间复杂度: O(N^2lgN)******- 空间复杂度: O(N)******

beats 25.82%

```python
class Solution(object):
    def shortestToChar(self, S, C):
        """
        :type S: str
        :type C: str
        :rtype: List[int]
        """
        lookup = collections.defaultdict(list)
        for i, c in enumerate(S):
            lookup[c].append(i)
            
        res = []
        for i, c in enumerate(S):
            if c == C:
                res.append(0)
            else:
                tmp = sorted(abs(idx-i) for idx in lookup[C])[0]
                res.append(tmp)
        return res
```


> 思路 2
******- 时间复杂度: O(N)******- 空间复杂度: O(N)******

就两种可能性，要么左边要么右边，用个prev记录一下

```
For each index S[i], let's try to find the distance to the next character C going left, and going right. 
The answer is the minimum of these two values.

When going left to right, we'll remember the index prev of the last character C we've seen. Then the answer is i - prev.

When going right to left, we'll remember the index prev of the last character C we've seen. Then the answer is prev - i.

We take the minimum of these two answers to create our final answer.
```

beats 91.61%

```python
class Solution(object):
    def shortestToChar(self, S, C):
        """
        :type S: str
        :type C: str
        :rtype: List[int]
        """
        prev = -sys.maxsize
        res = []
        for i, c in enumerate(S):
            if c == C: 
                prev = i
            res.append(i - prev)

        prev = sys.maxsize
        for i in range(len(S) - 1, -1, -1):
            if S[i] == C: 
                prev = i
            res[i] = min(res[i], prev - i)

        return res
```
