Given a string s
and a character c
that occurs in s
, return an array of integers answer
where answer.length == s.length
and answer[i]
is the shortest distance from s[i]
to the character c
in s
.
Example 1:
Input: s = "loveleetcode", c = "e" Output: [3,2,1,0,1,0,0,1,2,2,1,0]
Example 2:
Input: s = "aaab", c = "b" Output: [3,2,1,0]
Constraints:
1 <= s.length <= 104
s[i]
andc
are lowercase English letters.c
occurs at least once ins
.
字符的最短距离。
给定一个字符串 S
和一个字符 C
。返回一个代表字符串 S
中每个字符到字符串 S
中的字符 C
的最短距离的数组。
我给出一个比较常规的思路。首先我们遍历一次input字符串,用hashmap记录每一个C的位置。第二遍遍历字符串的时候,对于每一个不是C的字母,我们比较一下当前这个字母的index和每一个字母C的index,找到其中的最小值。
时间O(n^2)
空间O(n)
Java实现
1 class Solution { 2 public int[] shortestToChar(String s, char c) { 3 int len = s.length(); 4 HashMap<Character, List<Integer>> map = new HashMap<>(); 5 List<Integer> list = new ArrayList<>(); 6 // mark the index of all the Cs 7 for (int i = 0; i < len; i++) { 8 if (s.charAt(i) == c) { 9 list.add(i); 10 } 11 } 12 map.put(c, list); 13 14 int[] res = new int[len]; 15 for (int i = 0; i < len; i++) { 16 if (s.charAt(i) != c) { 17 int min = Integer.MAX_VALUE; 18 for (int index : map.get(c)) { 19 min = Math.min(min, Math.abs(index - i)); 20 } 21 res[i] = min; 22 } else if (s.charAt(i) == c) { 23 res[i] = 0; 24 } 25 } 26 return res; 27 } 28 }