无尽算法之 字符的最短距离

给定一个字符串 S 和一个字符 C。返回一个代表字符串 S 中每个字符到字符串 S 中的字符 C 的最短距离的数组。

示例 1:

输入: S = “loveleetcode”, C = ‘e’
输出: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
说明:
3
字符串 S 的长度范围为 [1, 10000]。
C 是一个单字符,且保证是字符串 S 里的字符。
S 和 C 中的所有字母均为小写字母。

思路:

从左往右遍历一遍, 再从右往左遍历一遍

题解:

class Solution {
    public int[] shortestToChar(String S, char C) {
        char[] s = S.toCharArray();
        int[] res = new int[S.length()];
        boolean flag = false;
        int count = 1;
        for(int i=0; i<s.length; i++){
            if(s[i] == C){
                flag = true;
                count = 0;
            }
            if(flag){
                res[i] = res[i] < count && res[i] != 0 ? res[i] : count;
                count ++;
            }
        }
        flag = false;
        for(int i = s.length-1; i >= 0; i--){
            if(s[i] == C){
                count = 0;
                flag = true;
            }
            if(flag){
                res[i] = res[i] < count && res[i] != 0 ? res[i] : count;
                count++;
            }
        }
        return res;
    }
}
发布了188 篇原创文章 · 获赞 323 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_33709508/article/details/104231243