给定一个字符串 S
和一个字符 C
。返回一个代表字符串 S
中每个字符到字符串 S
中的字符 C
的最短距离的数组。
示例 1:
输入: S = "loveleetcode", C = 'e' 输出: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
说明:
- 字符串
S
的长度范围为[1, 10000]
。 C
是一个单字符,且保证是字符串S
里的字符。S
和C
中的所有字母均为小写字母。
public static int[] shortestToChar(String S, char C) {
int[] result = new int[S.length()] ;
char[] chars = S.toCharArray();
int[] loan = new int[S.length()];
//当前两数之差
int x = 0;
//loan数组存放字符C的位置
for(int i = 0 ; i < chars.length ; i++){
if(chars[i] == C){
loan[x]=i;
x++;
}
}
for(int i = 0 ; i < chars.length ; i++){
//y为C与loan里面每一个数比较后的最小值
int y = Integer.MAX_VALUE;
if(chars[i] == C){
result[i] = 0;
}else{
//计算每个C的位置与loan数组中的最短距离,遍历次数为loan中非0个数
for(int j = 0 ; j < x; j++ ){
//s为当前字符和loan数组中元素的距离
int s = 0;
if(i<loan[j]){
s = loan[j] - i;
}else{
s = i - loan[j];
}
if(s < y){
y = s;
}
}
result[i] = y;
}
}
return result;
}