1. 程式人生 > >leetcode 821. 字符的最短距離(Shortest Distance to a Character)

leetcode 821. 字符的最短距離(Shortest Distance to a Character)

pre love toc ref string 距離 lis sta 一個

目錄

  • 題目描述:
  • 示例 1:
  • 解法:

題目描述:

給定一個字符串 S 和一個字符 C。返回一個代表字符串 S 中每個字符到字符串 S 中的字符 C 的最短距離的數組。

示例 1:

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

說明:

  • 字符串 S 的長度範圍為 [1, 10000]
  • C 是一個單字符,且保證是字符串 S 裏的字符。
  • SC 中的所有字母均為小寫字母。

解法:

class Solution {
public:
    vector<int> shortestToChar(string S, char C) {
        int sz = S.size();
        vector<int> res(sz, sz);
        int pre = -sz;
        for(int i = 0; i < sz; i++){
            if(S[i] == C){
                pre = i;
            }
            res[i] = min(res[i], i - pre);
        }
        
        int pst = 2*sz;
        for(int i = sz-1; i >= 0; i--){
            if(S[i] == C){
                pst = i;
            }
            res[i] = min(res[i], pst - i);
        }
        return res;
    }
};

leetcode 821. 字符的最短距離(Shortest Distance to a Character)