LeetCode 821 Shortest Distance to a Character
题目分析
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.
个人感觉还是比较好懂的,给定一个字符串和字符,找出每个位置的字符距离给定字符串的最小距离。
思考
数目不是太大,我选择暴力求解,思路简单易懂,从字符位置分别向左向右搜索,遇到给定字符就停止搜索,计算两个下标之间的距离,时间复杂度 O(n2) O ( n 2 ) 。
代码实现
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;
}
};
感想
数据两经过估计如果不会太大的话可以直接使用暴力求解,也是可以接受的。其实这个题想要改进的话,可以考虑使用辅助数组记录给定字符所有的下标,具体的思路没想粗来,还需多加练习啊。