码迷,mamicode.com
首页 > 其他好文 > 详细

(Easy) Shortest distance to Character LeetCode

时间:2019-08-22 19:13:00      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:title   list()   max   BMI   note   iss   tmp   return   nta   

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;
        
    }
}

 

(Easy) Shortest distance to Character LeetCode

标签:title   list()   max   BMI   note   iss   tmp   return   nta   

原文地址:https://www.cnblogs.com/codingyangmao/p/11395919.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!