821. 字符的最短距离

给定一个字符串 S 和一个字符 C。返回一个表明字符串 S 中每一个字符到字符串 S 中的字符 C 的最短距离的数组。java

示例 1:数组

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

说明:code

  1. 字符串 S 的长度范围为 [1, 10000]
  2. C 是一个单字符,且保证是字符串 S 里的字符。
  3. S 和 C 中的全部字母均为小写字母。

 

public static int[] shortestToChar(String S, char C) {

        int[] result = new int[S.length()] ;
        char[] chars = S.toCharArray();
        int[] loan = new int[S.length()];
        //当前两数之差
        int x = 0;
        //loan数组存放字符C的位置
        for(int i = 0 ; i < chars.length ; i++){
            if(chars[i] == C){
                loan[x]=i;
                x++;
            }
        }
        for(int i = 0 ; i < chars.length ; i++){
            //y为C与loan里面每个数比较后的最小值
            int y = Integer.MAX_VALUE;
            if(chars[i] == C){
                result[i] = 0;
            }else{
                //计算每一个C的位置与loan数组中的最短距离,遍历次数为loan中非0个数
                for(int j = 0 ; j < x; j++ ){
                    //s为当前字符和loan数组中元素的距离
                    int s = 0;
                    if(i<loan[j]){
                        s = loan[j] - i;
                    }else{
                        s = i - loan[j];
                    }
                    if(s < y){
                        y = s;
                    }
                }
                result[i] = y;
            }
        }
        return result;
    }