LeetCode821字符串的最短距离----双指针、两次遍历

题目表述

给你一个字符串 s 和一个字符 c ,且 c 是 s 中出现过的字符。

返回一个整数数组 answer ,其中 answer.length == s.length 且 answer[i] 是 s 中从下标 i 到离它 最近 的字符 c 的 距离 。

两个下标 i 和 j 之间的 距离 为 abs(i - j) ,其中 abs 是绝对值函数。

示例:

输入:s = "loveleetcode", c = "e"

输出:[3,2,1,0,1,0,0,1,2,2,1,0]

解释:字符 'e' 出现在下标 3、5、6 和 11 处(下标从 0 开始计数)。
距下标 0 最近的 'e' 出现在下标 3 ,所以距离为 abs(0 - 3) = 3 。
距下标 1 最近的 'e' 出现在下标 3 ,所以距离为 abs(1 - 3) = 2 。
对于下标 4 ,出现在下标 3 和下标 5 处的 'e' 都离它最近,但距离是一样的 abs(4 - 3) == abs(4 - 5) = 1 。
距下标 8 最近的 'e' 出现在下标 6 ,所以距离为 abs(8 - 6) = 2 。

双指针

该题我使用了双指针来解,想的就是找到两个字符c的下标,初始化一个preIndex为-n,一个right,代表当前字符左边的c和当前字符右边c的位置。比较当前字符距离哪个字符c距离最近,取最近的距离即可。
最后若right == n 且 right != preIndex + 1,则说明最后一个字符c不是在字符串末尾,只需从当前下标位置计算与preIndex的距离即可。
代码里面使用了双重循环,但本质上算法时间复杂度为O(n)。该题与官解思路一样,代码实现有所差异。下面是自己写的代码和管解,相比还是管解更容易理解。
双指针解法:

class Solution { public int[] shortestToChar(String s, char c) { int n = s.length(); int[] answer = new int[n]; int preIndex = -n; int left = 0,right = 0; while(right < n){ while(right < n && s.charAt(right) != c){ right++; } if(right == n) break; while(left <= right){ answer[left] = Math.min(left - preIndex,right - left); left++; } preIndex = right; right++; } if(preIndex + 1 < right){ while(left < n){ answer[left] = left - preIndex; left++; } } return answer; } }

官方解法:

class Solution { public int[] shortestToChar(String s, char c) { int n = s.length(); int[] ans = new int[n]; for (int i = 0, idx = -n; i < n; ++i) { if (s.charAt(i) == c) { idx = i; } ans[i] = i - idx; } for (int i = n - 1, idx = 2 * n; i >= 0; --i) { if (s.charAt(i) == c) { idx = i; } ans[i] = Math.min(ans[i], idx - i); } return ans; } }

__EOF__

本文作者Younger
本文链接https://www.cnblogs.com/youngerwb/p/16167074.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   YoungerWb  阅读(38)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示