目录结构
1.题目
给定一个字符串 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
中的所有字母均为小写字母。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-distance-to-a-character
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
离当前字符最近的字符串可能出现在其前面,也可能在其后面,故顺序和逆序分别计算在前和在后的距离,最后取较小值即可。
public class Solution821 {
@Test
public void test821() {
String S = "loveleetcode";
char C = 'e';
System.out.println(Arrays.toString(shortestToChar(S, C)));
}
public int[] shortestToChar(String S, char C) {
int len = S.length();
int[] result = new int[len];
int prev = -len;
for (int i = 0; i < len; ++i) {
if (S.charAt(i) == C) {
prev = i;
}
result[i] = i - prev;
}
prev = 2 * len;
for (int i = len - 1; i >= 0; --i) {
if (S.charAt(i) == C) {
prev = i;
}
result[i] = Math.min(result[i], prev - i);
}
return result;
}
}
- 时间复杂度:
- 空间复杂度: