description of problem
Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s.
The distance between two indices i and j is abs(i - j), where abs is the absolute value function.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-distance-to-a-character
Chinese version
给你一个字符串 s 和一个字符 c ,且 c 是 s 中出现过的字符。
返回一个整数数组 answer ,其中 answer.length == s.length 且 answer[i] 是 s 中从下标 i 到离它 最近 的字符 c 的 距离 。
两个下标 i 和 j 之间的 距离 为 abs(i - j) ,其中 abs 是绝对值函数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-distance-to-a-character
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
example
Input: s = "loveleetcode", c = "e"
Output: [3,2,1,0,1,0,0,1,2,2,1,0]
Explanation: The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed).
The closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3.
The closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2.
For index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) = 1.
The closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-distance-to-a-character
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
intuition
- we need to traverse all elments to find the shortest distance
- the shortest character c may be in the left or in the right
The codes for above problem
#include <vector>
#include <iostream>
#include <string>
#include <climits>
using namespace std;
class Solution {
public:
vector<int> shortestToChar(string s, char c) {
vector<int> res;
int n = s.size();
for (int i =0; i < n; i++) {
int distance{0};
distance = short_distance(s, c, i);
res.push_back(distance);
}
return res;
}
int short_distance(string s, char c, int i) {
int n = s.size();
// the biggest integer to initialize the distance
int distance = INT_MAX; // easy to make rookie mistake
for (int j = i; j < n; j++) {
if (s[j] == c) {
distance = j - i;
break;
}
}
for (int j = i; j >= 0; j--) {
if (s[j] == c) {
distance = min(distance, i - j);
break;
}
}
return distance;
}
};
int main()
{
Solution s;
string s1 = "loveleetcode";
char c1 = 'e';
vector<int> res1 = s.shortestToChar(s1, c1);
for (int i = 0; i < res1.size(); i++) {
cout << res1[i] << " ";
}
cout << endl;
return 0;
}
The results:
3 2 1 0 1 0 0 1 2 2 1 0