821.字符的最短距离

131 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

题目

821.字符的最短距离

题目大意

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

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

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

样例

示例 1:

输入:s = "loveleetcode", c = "e"
输出:[3,2,1,0,1,0,0,1,2,2,1,0]
解释:字符 'e' 出现在下标 35611 处(下标从 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

示例 2:

输入:s = "aaab", c = "b"
输出:[3,2,1,0]

数据规模

提示:

  • 1<=s.length<=1041 <= s.length <= 10^4
  • s[i]c 均为小写英文字母
  • 题目数据保证 cs 中至少出现一次

思路

可以考虑将s中所有等于c的元素的下标存储到id中,然后对于s的所有元素,如果s[i]==c,那么ans[i]=0;否则访问所有的id元素找到距离i最近的值。最后返回ans即可。

// short int long float double bool char string void
// array vector stack queue auto const operator
// class public private static friend extern 
// sizeof new delete return cout cin memset malloc
// relloc size length memset malloc relloc size length
// for while if else switch case continue break system
// endl reverse sort swap substr begin end iterator
// namespace include define NULL nullptr exit equals 
// index col row arr err left right ans res vec que sta
// state flag ch str max min default charray std
// maxn minn INT_MAX INT_MIN push_back insert
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int>PII;
typedef pair<int, string>PIS;
const int maxn=1e6+50;//注意修改大小
long long read(){long long x=0,f=1;char c=getchar();while(!isdigit(c)){if(c=='-') f=-1;c=getchar();}while(isdigit(c)){x=x*10+c-'0';c=getchar();}return x*f;}
ll qpow(ll x,ll q,ll Mod){ll ans=1;while(q){if(q&1)ans=ans*x%Mod;q>>=1;x=(x*x)%Mod;}return ans%Mod;}

class Solution {
public:
    vector<int> shortestToChar(string s, char c) {
        int n=s.length();
        vector<int>id;
        for(int i=0;i<n;i++){
            if(s[i]==c){
                id.push_back(i);
            }
        }
        vector<int>ans(n);
        for(int i=0;i<n;i++){
            int maxx=1e9;
            if(s[i]==c){
                ans[i]=0;
                continue;
            }
            for(auto it:id){
                maxx=min(maxx,abs(i-it));
            }
            ans[i]=maxx;
        }
        return ans;
    }
};

可以考虑优化:

问题可以转换成,对s的每个下标ii,求

  • s[i]s[i]到其左侧最近的字符cc的距离
  • s[i]s[i]到其右侧最近的字符cc的距离

这样时间复杂度就可以优化到O(n)O(n)