# 821.Shortest Distance to a Character

**821.Shortest Distance to a Character**

难度:Easy

> 给定一个字符串 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 中的所有字母均为小写字母。

代码如下：

```
class Solution {
public:
    vector<int> shortestToChar(string S, char C) {
        vector<int> cc;
        int len=S.size();
        vector<int> index;
        for(auto i:S)
            if(i==C) {cc.push_back(0);
                      index.push_back(cc.size()-1);}
            else cc.push_back(len);
        int start=1;
        for(int i=index[0]+1;i<len;i++)
            if(cc[i]) cc[i]=start++;
            else start=1;
        start=1;
        for(int i=index[index.size()-1]-1;i>=0;i--)
            if(cc[i]) cc[i]=min(cc[i],start++);
            else start=1;
        return cc;
    }
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/821.shortest_distance_to_a_character.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
