leetcode 算法题821 (简单214) 字符的最短距离
- 题目介绍
给定一个字符串 S 和一个字符 C。
返回一个代表字符串 S 中每个字符到字符串 S 中的字符 C 的最短距离的数组。
- 示例
输入: S = “loveleetcode”, C = ‘e’
输出: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
字符串 S 的长度范围为 [1, 10000]。
C 是一个单字符,且保证是字符串 S 里的字符。
S 和 C 中的所有字母均为小写字母。
- 解法一
/**
* @param {string} S
* @param {character} C
* @return {number[]}
*/
var shortestToChar = function(S, C) {
let i = S.indexOf(C), temp = [], indexs = [], j = 0;
while(i > -1) {
indexs.push(i);
i = S.indexOf(C, i + 1);
}
i = 0;
console.log(indexs)
while(i < S.length) {
if(j < indexs.length && i > indexs[j]) {
j++;
}
if(j === 0) {
temp[i] = indexs[j] - i;
} else if(j === indexs.length) {
temp[i] = i - indexs[j - 1];
} else {
temp[i] = Math.min(indexs[j] - i, i - indexs[j - 1]);
}
i++;
}
return temp;
};
执行用时 : 64 ms, 在所有 JavaScript 提交中击败了99.03%的用户
内存消耗 : 36.3 MB, 在所有 JavaScript 提交中击败了47.37%的用户