Skip to content

Commit 56edba7

Browse files
committed
Add two C++ solutions for 91algo day2 (leetcode821).
1 parent 0cf58dc commit 56edba7

File tree

2 files changed

+96
-0
lines changed

2 files changed

+96
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#include <vector>
2+
#include <unordered_map>
3+
#include <algorithm>
4+
#include <iostream>
5+
using namespace std;
6+
7+
class Solution {
8+
public:
9+
vector<int> shortestToChar(string s, char c) {
10+
// 题意: 计算 abs[i] = indexGap(i, nearest_c), 1 <= s.length <= 10^4
11+
// 输出 abs[i]的数组
12+
vector<int> indexes; // indexes of char c
13+
for (int i = 0; i < s.size(); i++)
14+
{
15+
if (s[i] == c) indexes.push_back(i);
16+
}
17+
vector<int> res;
18+
for (int i = 0; i < s.size(); i++)
19+
{
20+
vector<int> gaps; // gap for char s[i] to char c
21+
for (auto index : indexes)
22+
gaps.push_back(abs(index - i));
23+
auto it = min_element(gaps.begin(), gaps.end());
24+
res.push_back(*it);
25+
}
26+
return res;
27+
}
28+
};
29+
30+
// Test
31+
int main()
32+
{
33+
Solution sol;
34+
string s = "loveleetcode";
35+
char c = 'e';
36+
auto res = sol.shortestToChar(s, c);
37+
for (auto &num : res)
38+
cout << num << endl;
39+
40+
return 0;
41+
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include <vector>
2+
#include <unordered_map>
3+
#include <algorithm>
4+
#include <iostream>
5+
using namespace std;
6+
7+
class Solution {
8+
public:
9+
vector<int> shortestToChar(string s, char c) {
10+
vector<int> gaps(s.size());
11+
vector<char> chars(s.begin(), s.end());
12+
13+
for (int i = 0; i < chars.size(); i++)
14+
{
15+
// 如果当前字符就是要搜索的字符c, 距离为 0
16+
if (chars[i] == c) gaps[i] = 0;
17+
else /* 否则分别向左、向右找最近的字符c */
18+
{
19+
int leftDistance = INT_MAX, rightDistance = INT_MAX;
20+
for (int left = i; left >= 0; left--)
21+
{
22+
if (chars[left] == c) // 向左找, 找到第一个
23+
{
24+
leftDistance = i - left;
25+
break;
26+
}
27+
}
28+
for (int right = i; right < chars.size(); right++) // 向右找, 找到第一个
29+
{
30+
if (chars[right] == c)
31+
{
32+
rightDistance = right - i;
33+
break;
34+
}
35+
}
36+
gaps[i] = min(leftDistance, rightDistance);
37+
}
38+
}
39+
40+
return gaps;
41+
}
42+
};
43+
44+
// Test
45+
int main()
46+
{
47+
Solution sol;
48+
string s = "loveleetcode";
49+
char c = 'e';
50+
auto res = sol.shortestToChar(s, c);
51+
for (auto &num : res)
52+
cout << num << endl;
53+
54+
return 0;
55+
}

0 commit comments

Comments
 (0)