美文网首页
2022-04-19 「821. 字符的最短距离」

2022-04-19 「821. 字符的最短距离」

作者: 柠香萌萌鸡 | 来源:发表于2022-04-19 09:24 被阅读0次

今日简单题:https://leetcode-cn.com/problems/shortest-distance-to-a-character/

今天做了一个复杂度过高的答案,基本是暴力解法了,然后得到了:


超时警告

记录下暴力思路:
1.第一次遍历数组,把字母c的下标记录下来;
2.第二次遍历数组,判断如果前面还有c,同时现在i和第1个c的距离超过了第2个c,就把第1个c换成第2个,然后把i到第1个c的距离存下来;

先贴下超时的答案,明天再研究下题解的双指针和双向遍历方法:

class Solution {
    public int[] shortestToChar(String s, char c) {
        int[] ch1 = new int[s.length()];
        int tail = 0;
        for (int i=0; i<s.length(); i++) {
            if (s.charAt(i) == c) {
                ch1[tail] = i;
                tail++;
            }
        }
        int[] ans = new int[s.length()];
        int head = 0;
        for (int k=0; k<s.length(); k++) {
            while (ch1[head+1] !=0) {
                if (Math.abs(k-ch1[head]) >= Math.abs(k-ch1[head+1])) {
                    head++;
                }
                ans[k] = Math.abs(k-ch1[head]);
            }
        }
        return ans;
    }
}

相关文章

网友评论

      本文标题:2022-04-19 「821. 字符的最短距离」

      本文链接:https://www.haomeiwen.com/subject/tqcsertx.html