Skip to content

Commit 4459ed2

Browse files
Bruce YangBruce Yang
Bruce Yang
authored and
Bruce Yang
committed
Add day2 post.
1 parent 5281429 commit 4459ed2

File tree

1 file changed

+110
-0
lines changed

1 file changed

+110
-0
lines changed

91algo/daily/posts/day2.md

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
# day2 - 821. 字符的最短距离[2021-09-11]
2+
3+
## 题目地址(821. 字符的最短距离)
4+
5+
https://leetcode-cn.com/problems/shortest-distance-to-a-character
6+
7+
8+
9+
## 思路
10+
11+
**题意**: 计算 `abs[i] = indexGap(i, 最近的字符c)`, 1 <= s.length <= 10^4
12+
输出 `abs[i]`的数组
13+
14+
### 解法: 双指针 中心扩展
15+
16+
使用一个结果数组 gaps[]
17+
18+
将string s转为字符数组,然后从前往后遍历。
19+
循环变量记作i, 对于每一趟:
20+
如果当前字符就是要搜索的字符c, 距离记为 0,否则分别向左、向右找最近的字符c。
21+
向左找, 找到第一个字符c, 将指针i与之的index之差记作leftDistance。
22+
向右找, 找到第一个字符c, 将指针i与之的index之差记作rightDistance。
23+
取两者的较小值。
24+
25+
依次填充 gaps[i] 的值即可。
26+
27+
28+
29+
## 代码
30+
31+
### 实现语言: C++
32+
33+
```cpp
34+
class Solution {
35+
public:
36+
vector<int> shortestToChar(string s, char c) {
37+
vector<int> gaps(s.size());
38+
vector<char> chars(s.begin(), s.end());
39+
40+
for (int i = 0; i < chars.size(); i++)
41+
{
42+
// 如果当前字符就是要搜索的字符c, 距离为 0
43+
if (chars[i] == c) gaps[i] = 0;
44+
else /* 否则分别向左、向右找最近的字符c */
45+
{
46+
int leftDistance = INT_MAX, rightDistance = INT_MAX;
47+
for (int left = i; left >= 0; left--)
48+
{
49+
if (chars[left] == c) // 向左找, 找到第一个
50+
{
51+
leftDistance = i - left;
52+
break;
53+
}
54+
}
55+
for (int right = i; right < chars.size(); right++) // 向右找, 找到第一个
56+
{
57+
if (chars[right] == c)
58+
{
59+
rightDistance = right - i;
60+
break;
61+
}
62+
}
63+
gaps[i] = min(leftDistance, rightDistance);
64+
}
65+
}
66+
67+
return gaps;
68+
}
69+
};
70+
```
71+
72+
代码已同步上传到: [leetcode-ac/91algo - github.com](https://github.com/yanglr/leetcode-ac/tree/master/91algo)
73+
74+
75+
76+
#### 复杂度分析
77+
78+
- 时间复杂度:O(n^2),其中 n 为字符串长度。
79+
- 空间复杂度:O(n)
80+
81+
82+
83+
### 暴力解法:
84+
85+
可以过,但比较慢。
86+
87+
```cpp
88+
class Solution {
89+
public:
90+
vector<int> shortestToChar(string s, char c) {
91+
// 题意: 计算 abs[i] = indexGap(i, nearest_c), 1 <= s.length <= 10^4
92+
// 输出 abs[i]的数组
93+
vector<int> indexes; // indexes of char c
94+
for (int i = 0; i < s.size(); i++)
95+
{
96+
if (s[i] == c) indexes.push_back(i);
97+
}
98+
vector<int> res;
99+
for (int i = 0; i < s.size(); i++)
100+
{
101+
vector<int> gaps; // gap for char s[i] to char c
102+
for (auto index : indexes)
103+
gaps.push_back(abs(index - i));
104+
auto it = min_element(gaps.begin(), gaps.end());
105+
res.push_back(*it);
106+
}
107+
return res;
108+
}
109+
};
110+
```

0 commit comments

Comments
 (0)