题目
给定一个字符串 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 中的所有字母均为小写字母。
相关话题:字符串
我的思路:先保存所有C的位置,然后对1~S.length() 与保存位置的距离求绝对值差,保存最小的。
我的代码:
class Solution {
public int[] shortestToChar(String S, char C) {
char[] ch = S.toCharArray();
int len = ch.length;
List<Integer> list = new ArrayList<>();
int[] distance = new int[len];
int index = len;
for (int i = 0 ; i < len ; i ++) {
if(ch[i]==C){
list.add(i);
}
}
for(int j = 0; j < len ; j ++){
index = len;
for (int i : list) {
index = Math.min(index, Math.abs(j-i));
}
distance[j] = index;
}
return distance;
}
}