Tuesday, September 8, 2020

LeetCode [821] Shortest Distance to a Character

 821. Shortest Distance to a Character

Easy

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.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
    public int[] shortestToChar(String S, char C) {
        int len = S.length();
        int[] ret = new int[len];

        int e = -1;
        for(int i=0; i<len; ++i)
        {
            if(S.charAt(i)==C) e = i;
            if(e==-1) ret[i] = len;
            else ret[i] = i-e;
        }

        e = len;
        for(int i=len-1; i>=0; --i)
        {
            if(S.charAt(i)==C) e = i;
            if(e<len) ret[i] = Math.min(ret[i], e-i);
        }

        return ret;
    }
}

No comments:

Post a Comment