821. Shortest Distance to a Character

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:

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

程序如下所示:

class Solution {
    public int[] shortestToChar(String S, char C) {
        List<Integer> list = new ArrayList<>();
        int len = S.length();
        for (int i = 0; i < len; ++ i){
            if (S.charAt(i) == C){
                list.add(i);
            }
        }
        int[] res = new int[len];
        Collections.sort(list);
        int size = list.size();
        int index = 0, bias = 0, tmp = Integer.MAX_VALUE, d = 0;
        for (int i = 0; i < len; ++ i){
            tmp = Integer.MAX_VALUE;
            bias = Math.abs(i - list.get(index));
            if (index + 1 < size){
                tmp = Math.abs(i - list.get(index+1));
                if (bias >= tmp){
                    index ++;
                }
            }
            res[d++] = Math.min(bias, tmp);
        }
        return res;
    }
}

你可能感兴趣的:(LeetCode)