版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/82983140
Description:
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:
Input: S = “loveleetcode”, C = ‘e’
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
Note:
- S string length is in [1, 10000].
- C is a single character, and guaranteed to be in string S.
- All letters in S and C are lowercase.
题意:给定一个字符串和一个字符,要求计算出字符串中所有字符距离给定字符的最近距离;
解法:最简单的方法就是对每一个字符,计算左右两边距离给定字符的最近的距离后,返回两者中较小的那个就是当前字符距离给定字符最近的那个距离;
Java
class Solution {
public int[] shortestToChar(String S, char C) {
int[] result = new int[S.length()];
for (int i = 0; i < S.length(); i++) {
int left = i;
int right = i;
while (left >= 0 && S.charAt(left) != C) left--;
while (right < S.length() && S.charAt(right) != C) right++;
int leftDis = left == -1 ? Integer.MAX_VALUE : i - left;
int rightDis = right == S.length() ? Integer.MAX_VALUE : right - i;
result[i] = Math.min(leftDis, rightDis);
}
return result;
}
}