需求:
给定一个字符串 s 和一个字符 c,且 c 是 s 中出现过的字符。
返回一个整数数组,answer,其中 answer.length == s.length 且 answer[i] 是 s 中下标 i 到离它最近的字符 c 的距离。
实现代码:
public static int[] minDistance(String s, char ch) {
if (s == null || s.length() <= 0) {
return new int[] {};
}
String c = String.valueOf(ch);
if (Boolean.FALSE == s.contains(c)) {
return new int[] {};
}
int[] answer = new int[s.length()];
s = s.replaceAll(c, "0");
int startIdx = s.indexOf("0");
int endIdx = s.indexOf("0");
for (int i = 0; i < s.length(); i++) {
int leftDistance = Math.abs(i - startIdx);
int rightDistance = Math.abs(i - endIdx);
if (i == endIdx) {
startIdx = endIdx;
endIdx = s.indexOf("0", endIdx + 1);
}
answer[i] = leftDistance < rightDistance ? leftDistance : rightDistance;
}
return answer;
}
public static void main(String[] args) {
int[] result = minDistance("loveleetcode", 'e');
if (result.length <= 0) {
System.out.println("source string is invalid");
} else {
System.out.println("minDistance: ");
for (int i = 0; i < result.length; i++) {
System.out.print(result[i] + ", ");
}
}
}
测试
输入:loveleetcode,e
输出:3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0