LeetCode

字符的最短距离

2019-07-11  本文已影响0人  习惯了_就好

给定一个字符串 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 中的所有字母均为小写字母。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-distance-to-a-character
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
    public int[] shortestToChar(String S, char C) {
        int length = S.length();
        int [] result = new int[length];
        List<Integer>list = new ArrayList<>();//是该字母的下标都存在list中
        
        for(int i = 0; i < length; i++){
            if(S.charAt(i) == C){
                result[i] = 0;
                list.add(i);
            }
        }
        
        int listLength = list.size();
        int minEindex = list.get(0);
        int maxEindex = list.get(listLength - 1);
        
        for(int i = 0; i < length; i++){
            if(S.charAt(i) != C){
                if(i < minEindex){//第一个该字母左边的
                    result[i] = minEindex - i;
                } else if(i > maxEindex){ //最后一个该字母右边的
                    result[i] = i - maxEindex;
                } else {//在中间的,只需和它前后的两个比较
                    int tempMax;
                    int tempMin;
                    for(int j = 0; j < listLength; j++){
                        if(list.get(j) > i){//找到第一个比它大的,那list中前一个就是比它小的
                            tempMax = list.get(j);
                            tempMin = list.get(j - 1);
                            result[i] = Math.min(tempMax - i, i - tempMin);
                            break;
                        }
                    }
                }
                
            }
        }
        return result;
    }
}

上一篇下一篇

猜你喜欢

热点阅读