给定一个字符串 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
中的所有字母均为小写字母。
思路:将字符串转数组,遍历取出包含字符的所有位置。循环比较字符所在位置和字符串内所有字符的位置,并取最小位置保存在数组中返回
class Solution {
public int[] shortestToChar(String S, char C) {
char[] str = S.toCharArray();
int[] shortest = new int[S.length()];
List<Integer> shortIs = new ArrayList<Integer>();
for(int i = 0;i < S.length();i++){
if(C == str[i])
shortIs.add(i);
}
for(int j=0;j < S.length();j++){
shortest[j] = shortLength(shortIs,j);
}
return shortest;
}
public int shortLength(List<Integer> A,int i){
int temp = 0;
int min = Math.abs(A.get(0)-i);
for(int a:A){
temp = Math.abs(a-i);
if(temp < min){
min = temp;
}
}
return min;
}
}