题目链接

字符的最短距离

题目描述

image.png

实现代码

个人实现思路:

  1. 首先遍历一次找到所有的c字符的位置存入数组cIndexes并记录其出现次数cLen;
  2. 第二次遍历,对所有位置的元素与cindexes中的c位置进行逐一比较取小值得出最后结果;

注意的点:

  1. 进行取小值对findC位置进行循环自增时判断是否已经到了最后一个;
  2. 考虑如下情况

    s = “bbba” c = ‘b’

实现代码:

  1. class Solution {
  2. public int[] shortestToChar(String s, char c) {
  3. int len = s.length();
  4. int[] results = new int[len];
  5. int[] cIndexed = new int[len];
  6. int cLen = 0;
  7. for(int i=0; i<len; i++) {
  8. if(s.charAt(i) == c) {
  9. cIndexed[cLen++] = i;
  10. }
  11. }
  12. int findC = 0;
  13. for(int i=0; i<len; i++) {
  14. char current = s.charAt(i);
  15. if(current == c) {
  16. continue;
  17. }
  18. if(findC == cLen-1) {
  19. results[i] = Math.abs(i - cIndexed[findC]);
  20. } else {
  21. while (Math.abs(i - cIndexed[findC]) >= Math.abs(i - cIndexed[findC + 1])) {
  22. findC++;
  23. if(findC == cLen - 1) {
  24. break;
  25. }
  26. }
  27. results[i] = Math.abs(i - cIndexed[findC]);
  28. }
  29. }
  30. return results;
  31. }
  32. }

官方思路:

  1. 分别找到每个位置从左看和从右看的最短距离,然后取最小

实现代码:

  1. class Solution {
  2. public int[] shortestToChar(String s, char c) {
  3. int n = s.length();
  4. int[] ans = new int[n];
  5. for (int i = 0, idx = -n; i < n; ++i) {
  6. if (s.charAt(i) == c) {
  7. idx = i;
  8. }
  9. ans[i] = i - idx;
  10. }
  11. for (int i = n - 1, idx = 2 * n; i >= 0; --i) {
  12. if (s.charAt(i) == c) {
  13. idx = i;
  14. }
  15. ans[i] = Math.min(ans[i], idx - i);
  16. }
  17. return ans;
  18. }
  19. }