(Easy) Shortest distance to Character LeetCode
Description:
Given a string S
and a character C
, return an array of integers representing the shortest distance from the character C
in the string.
Example 1:
Input: S = "loveleetcode", C = 'e' Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
Note:
S
string length is in[1, 10000].
C
is a single character, and guaranteed to be in stringS
.- All letters in
S
andC
are lowercase.
Accepted
42.5K
Submissions
66.4K
Seen this question in a real interview before?
Solution:
class Solution { public int[] shortestToChar(String S, char C) { ArrayList <Integer> arr = new ArrayList(); int[] res = new int[S.length()]; for(int i = 0; i<S.length(); i++){ if(S.charAt(i) == C){ arr.add(i); } } for(int i = 0; i<S.length(); i++){ int tmp = Integer.MAX_VALUE; for(int j = 0; j<arr.size();j++ ){ if(Math.abs(arr.get(j)-i)<tmp){ tmp = Math.abs(arr.get(j)-i); } } res[i] =tmp; } return res; } }