Leetcode 821:字符的最短距离

题目描述

给定一个字符串 S 和一个字符 C。返回一个代表字符串 S 中每个字符到字符串 S 中的字符 C 的最短距离的数组。

示例 1:

输入: S = "loveleetcode", C = 'e'
输出: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]

说明:

  1. 字符串 S 的长度范围为 [1, 10000]
  2. C 是一个单字符,且保证是字符串 S 里的字符。
  3. S 和 C 中的所有字母均为小写字母。

解题思路

思路与https://blog.csdn.net/weixin_35338624/article/details/89289949一样,都是设置两个指针,分别指向两个最大间隔的C的位置

vector<int> shortestToChar(string S, char C) {
        vector<int> ans;
        int pre = 0,pos = 0,len = S.length();
        int fir = INT_MAX,las = INT_MIN;
        while(pos<len){
            if(S[pre] != C) pre = pos;
            else{
                if(S[pos] == C){
                    for(int i=pre;i<pos;i++) ans.push_back(min(i-pre,pos-i));
                    pre = pos;
                }
            }
            if(S[pre] == C)fir = min(fir,pre);
            if(S[pos] == C)las = max(las,pos);
            pos++;
        }
        // cout<<fir<<" "<<las<<endl;
        for(int i=fir;i>0;i--) ans.insert(ans.begin(),fir-i+1);
        for(int i=las;i<len;i++) ans.push_back(i-las);
        return ans;
    }

猜你喜欢

转载自blog.csdn.net/weixin_35338624/article/details/89366266