leetcode_字符的最短距离

题目:

给定一个字符串 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 中的所有字母均为小写字母

解答

 1 class Solution {
 2     public int[] shortestToChar(String S, char C) {
 3         
 4         int[] result = new int[S.length()];
 5 
 6         List<Integer> rlist = new ArrayList<>();
 7         for (int i = 0; i < S.length(); i++) {
 8             if (S.charAt(i) == C) {
 9                 rlist.add(i);
10             }
11         }
12         for (int i = 0; i < S.length(); i++) {
13             int misDis = Integer.MAX_VALUE;
14             for (int a : rlist) {
15                 misDis = Math.min(misDis, Math.abs(a - i));
16             }
17             result[i] = misDis;
18         }
19 
20         return result;
21 
22     
23     }
24 }

猜你喜欢

转载自www.cnblogs.com/freeair/p/9051773.html