Skip to content

Latest commit

 

History

History
 
 

821. Shortest Distance to a Character

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string.

Example 1:

Input: S = "loveleetcode", C = 'e'
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]

 

Note:

  1. S string length is in [1, 10000].
  2. C is a single character, and guaranteed to be in string S.
  3. All letters in S and C are lowercase.

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(), prevJ;
        vector<int> ans(N);
        for (int i = 0, j = -1; i < N; ++i) {
            if (i > j) {
                prevJ = j;
                do { ++j; } while (j < N && S[j] != C);
            }
            ans[i] = min(j == N ? INT_MAX : j - i, prevJ == -1 ? INT_MAX : i - prevJ);
        }
        return ans;
    }
};