Java實現 LeetCode 821 字符的最短距離(暴力)

821. 字符的最短距離

給定一個字符串 S 和一個字符 C。返回一個代表字符串 S 中每個字符到字符串 S 中的字符 C 的最短距離的數組。

示例 1:

輸入: S = “loveleetcode”, C = ‘e’
輸出: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
說明:

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

class Solution {
     public int[] shortestToChar(String s, char c) {
        int len = s.length();
        int[] arr = new int[len];
        int lastIdx = -1, nextIdx = s.indexOf(c);

        for(int i=0; i<len; i++){
            if(nextIdx > -1 && i > nextIdx){
                lastIdx = nextIdx;
                nextIdx = s.indexOf(c, i);
            }

            if(nextIdx > -1 && lastIdx > -1){
                arr[i] = Math.min(i-lastIdx, nextIdx-i);
            } else if(lastIdx == -1){
                arr[i] = nextIdx-i;
            } else if(nextIdx == -1){
                arr[i] = i-lastIdx;
            }
        }

        return arr;
    }

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