821. 字符的最短距離-----【leetcode】刷題日誌

題目

給定一個字符串 S 和一個字符 C。返回一個代表字符串 S 中每個字符到字符串 S 中的字符 C 的最短距離的數組。
示例 1:
輸入: S = “loveleetcode”, C = ‘e’
輸出: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
說明:

  1. 字符串 S 的長度範圍爲 [1, 10000]。
  2. C 是一個單字符,且保證是字符串 S 裏的字符。
  3. S 和 C 中的所有字母均爲小寫字母。

相關話題:字符串


我的思路:先保存所有C的位置,然後對1~S.length() 與保存位置的距離求絕對值差,保存最小的。


我的代碼:

class Solution {
    public int[] shortestToChar(String S, char C) {
        char[] ch = S.toCharArray();

        int len = ch.length;

        List<Integer> list = new ArrayList<>();

        int[] distance = new int[len];      

        int index = len;

        for (int i = 0 ; i < len ; i ++) {
            if(ch[i]==C){
                list.add(i);
            }
        }

        for(int j = 0; j < len ; j ++){

            index = len;

            for (int i : list) {

                index = Math.min(index, Math.abs(j-i));
            }

            distance[j] = index;

        }


        return distance;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章