Shortest Distance to a Character-LeetCode#821

821. Shortest Distance to a Character

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.
给定字符串S和字符C,返回一个整数数组,表示字符串中字符C的最短距离。
public class ShortestDistanceToACharacter {
    public int[] shortestToChar(String S, char C) {
        int[] res = new int[S.length()];
        List<Integer> tempList = new ArrayList<>();
        for (int i = 0; i < S.toCharArray().length; i++) {
            if (S.toCharArray()[i] == C) {
                tempList.add(i);
            }
        }
        for (int i = 0; i < S.toCharArray().length; i++) {
            int min = S.length();
            for (int j = 0; j < tempList.size(); j++) {
                min = Math.min(Math.abs(tempList.get(j) - i), min);
            }
            res[i] = min;
        }
        return res;
    }
    public static void main(String[] args) {
        ShortestDistanceToACharacter shortestDistanceToACharacter = new ShortestDistanceToACharacter();
        shortestDistanceToACharacter.shortestToChar("loveleetcode", "e".toCharArray()[0]);
    }
}

用的方法很蠢啊。。。学习一下其他方法

文章已创建 112

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部