Skip to content

Latest commit

 

History

History

821

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the shortest distance from s[i] to the character c in s.

 

Example 1:

Input: s = "loveleetcode", c = "e"
Output: [3,2,1,0,1,0,0,1,2,2,1,0]

Example 2:

Input: s = "aaab", c = "b"
Output: [3,2,1,0]

 

Constraints:

  • 1 <= s.length <= 104
  • s[i] and c are lowercase English letters.
  • c occurs at least once in s.

Companies:
Bloomberg

Solution 1.

// OJ: https://leetcode.com/problems/shortest-distance-to-a-character/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    vector<int> shortestToChar(string s, char c) {
        int N = s.size(), prev = -N, next = 0;
        vector<int> ans(N);
        for (int i = 0; i < N; ++i) {
            while (next < N && s[next] != c) ++next; 
            if (next == N) next = N + N;
            ans[i] = min(i - prev, next - i);
            if (s[i] == c) prev = i, next++;
        }
        return ans;
    }
};