字符的最短距离

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

示例 1:

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

说明:

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

思路:将字符串转数组,遍历取出包含字符的所有位置。循环比较字符所在位置和字符串内所有字符的位置,并取最小位置保存在数组中返回

class Solution {
    public int[] shortestToChar(String S, char C) {
        char[] str = S.toCharArray();
        int[] shortest = new int[S.length()];
        List<Integer> shortIs = new ArrayList<Integer>();
        for(int i = 0;i < S.length();i++){
            if(C == str[i])
                shortIs.add(i);
        }
        for(int j=0;j < S.length();j++){
             shortest[j] = shortLength(shortIs,j);
        }
       return shortest;
    }
    
    public int shortLength(List<Integer> A,int i){
        int temp = 0;
        int min = Math.abs(A.get(0)-i);
        for(int a:A){
            temp = Math.abs(a-i);
            if(temp < min){
                min = temp;
            }
        }
        return min;
    }
}

猜你喜欢

转载自blog.csdn.net/zbuffalo/article/details/84393777