给定一个字符串S和一个字符串中的字符C,求该字符串中每个字符到该字符串中字符C的最短距离的数组。如S=”loveleetcode”,C=”e”,则结果为[3,2,1,0,1,0,0,1,2,2,

public static void main(String[] args) {
 String s = "loveleetcode";
char c = 'e';
List arr = new ArrayList<>();
char[] chrs = s.toCharArray();
for (int i = 0; i < s.length(); i++) {
    int start = i;
    int distance = countDistance(s, c, i);
    arr.add(distance);
}
System.out.println(arr);
}
public static int countDistance(String s, char c, int i) {
    int count = 0;
    for (int j = i; j < s.length(); j++) {
        if (s.charAt(j) == c){
            return j - i;
        }
    }
    return 0;
}

[3, 2, 1, 0, 1, 0, 0, 4, 3, 2, 1, 0] 

你可能感兴趣的:(给定一个字符串S和一个字符串中的字符C,求该字符串中每个字符到该字符串中字符C的最短距离的数组。如S=”loveleetcode”,C=”e”,则结果为[3,2,1,0,1,0,0,1,2,2,)