题目

Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the shortest distance from s[i] to the character c in s.

Example 1:

  1. Input: s = "loveleetcode", c = "e"
  2. Output: [3,2,1,0,1,0,0,1,2,2,1,0]

Example 2:

  1. Input: s = "aaab", c = "b"
  2. Output: [3,2,1,0]

Constraints:

  • 1 <= s.length <= 10^4
  • s[i] and c are lowercase English letters.
  • c occurs at least once in s.

题意

根据字符串s生成数组arr,arr[i]表示s中下标为i的字符到距离它最近的字符c的距离。

思路

维护两个数组left和right。left[i]表示下标i的元素到它左边最近的c的距离,right[i]表示下标i的元素到它右边最近的c的距离,最后比较left[i]和right[i]即可。


代码实现

Java

  1. class Solution {
  2. public int[] shortestToChar(String s, char c) {
  3. int[] left = new int[s.length()], right = new int[s.length()];
  4. int dl = -1, dr = -1;
  5. for (int i = 0; i < s.length(); i++) {
  6. if (s.charAt(i) == c) {
  7. dl = 0;
  8. } else {
  9. left[i] = dl == -1 ? Integer.MAX_VALUE : ++dl;
  10. }
  11. int j = s.length() - 1 - i;
  12. if (s.charAt(j) == c) {
  13. dr = 0;
  14. } else {
  15. right[j] = dr == -1 ? Integer.MAX_VALUE : ++dr;
  16. }
  17. }
  18. int[] ans = new int[s.length()];
  19. for (int i = 0; i < ans.length; i++) {
  20. ans[i] = Math.min(left[i], right[i]);
  21. }
  22. return ans;
  23. }
  24. }