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

}
原创文章 1954 获赞 3万+ 访问量 730万+

猜你喜欢

转载自blog.csdn.net/a1439775520/article/details/106033417