LeetCode 821 Shortest Distance to a Character
topic analysis
Given a string
S
and a characterC
, return an array of integers representing the shortest distance from the characterC
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 stringS
.- All letters in
S
andC
are lowercase.
Personally, it is relatively easy to understand. Given a string and characters, find the minimum distance between the characters in each position and the given string.
think
The number is not too large, I choose to solve it by violence, the idea is simple and easy to understand, search from left to right from the character position, stop the search when a given character is encountered, calculate the distance between the two subscripts, time complexity 。
Code
class Solution {
public:
vector<int> shortestToChar(string S, char C) {
int len = S.length();
// 选取一个比较大的数字
vector<int> result(len, 30000);
// 开始暴力
for (int i = 0; i < len; ++i) {
for (int j = i; j < len; ++j) {
// 搜索到字符就可以停止访问
if (S[j] == C) {
result[i] = min(j - i, result[i]);
break;
}
}
for (int j = i; j >= 0; --j) {
// 同等思想
if (S[j] == C) {
result[i] = min(i - j, result[i]);
break;
}
}
}
return result;
}
};
thoughts
It is also acceptable to use violence to solve the data directly if it is estimated that it is not too large. In fact, if you want to improve this question, you can consider using an auxiliary array to record all the subscripts of a given character. The specific ideas are not rough, and more practice is needed.