(Easy) Shortest distance to Character LeetCode

Posted codingyangmao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(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;
        
    

 

以上是关于(Easy) Shortest distance to Character LeetCode的主要内容,如果未能解决你的问题,请参考以下文章

1046 Shortest Distance (20point(s)) Easy only once *数组预处理问题

1046 Shortest Distance (20分)

Shortest Distance

pat Shortest Distance (20)

1046 Shortest Distance (20 分)

LeetCode 821. Shortest Distance to a Character