(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:

  1. S string length is in [1, 10000].
  2. C is a single character, and guaranteed to be in string S.
  3. All letters in S and C 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;
        
    }
}

 

posted @ 2019-08-22 17:57  CodingYM  阅读(155)  评论(0编辑  收藏  举报