Given a string S
and a character C
, return an array of integers representing the shortest distance from the character C
in the string.
Example 1:
Note:
S
string length is in[1, 10000].
C
is a single character, and guaranteed to be in stringS
.- All letters in
S
andC
are lowercase.
public int[] shortestToChar(String S, char C) {
char[] arr = S.toCharArray();
// 把string转换成char数组
int[] distance = new int[arr.length];
// distance 是返回的距离数组
ArrayList<Integer> al1 = new ArrayList<Integer>();
// al1 作为索引来保存目标C在arr数组中的位置
for (int i = 0; i < arr.length; i++) {
if (arr[i] == C) {
distance[i] = 0;
al1.add(i);
// 循环一次,记录目标字符的位置;
}
}
int index = 0;
// 第二次循环,对比当前位置i与相邻的index之间的距离
// 有几种情况:aabaa 目标字符在中间
//System.out.println("maxindex " + al1.get(al1.size() - 1) + " num" + al1.size());
for (int i = 0; i < arr.length; i++) {
// 超出界限
if (i > al1.get(al1.size() - 1)) {
distance[i] = i - al1.get(al1.size() - 1);
}
// 在界限之内
// 在第一个index之前
if (i < al1.get(0)) {
distance[i] = (char) (al1.get(0) - i);
}
// 当刚好到了index的时候,更新index
if ((i == al1.get(index)) && index < al1.size() - 1) {
index = index + 1;
}
// 有多个index并且在几个index之间
if (index > 0 && i > al1.get(index - 1) && i < al1.get(index)) {
int disR = (al1.get(index) - i);
int disL = i - al1.get(index - 1);
int min = Math.min(disL, disR);
//System.out.println("L" + disL + "R" + disR + " min" + min);
distance[i] = min;
}
}
return distance;
}