美文网首页LeetCode
字符的最短距离

字符的最短距离

作者: 习惯了_就好 | 来源:发表于2019-07-11 18:03 被阅读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;
    }
}

相关文章

  • 字符的最短距离

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

  • 字符的最短距离

    题目: 题目的理解: 获取C在S中的所有索引L,然后每一个字符与L进行相减并求绝对值,获取最小的值。 python...

  • LeetCode 821. 字符的最短距离

    题目地址(821. 字符的最短距离) https://leetcode-cn.com/problems/short...

  • 821. 字符的最短距离

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

  • 最短的距离

    火车站左转到汽车站然后又回到火车站出站口,全程0.5公里。有点意思,哎,我排队大约1小时多。不过还好,又轮一站...

  • Leetcode 821. 字符的最短距离

    题目表述难度:简单 给定一个字符串 S 和一个字符 C。返回一个代表字符串 S 中每个字符到字符串 S 中的字符 ...

  • 821. 字符的最短距离(Python)

    题目 难度:★★☆☆☆类型:字符串 给定一个字符串 S 和一个字符 C。返回一个代表字符串 S 中每个字符到字符串...

  • LeetCode-821-字符的最短距离

    解题思路: 常规解法:先遍历一遍找到S中等于C的下标,再遍历一次S计算最短距离; 指针双向遍历:当S中s等于C时,...

  • 你与知识跃迁之间的距离,只差“联机学习”

    点与点之间的距离,最短是直线; 路径很多,最短距离只有一个; 你与知识跃迁的最短距离,就是联机学习。 “呀,联机学...

  • 243. Shortest Word Distance

    给定一个字符串数组 wordsDict,和已经存在于数组中的两个不同的字符串,返回列表中两个单词之间的最短距离。 ...

网友评论

    本文标题:字符的最短距离

    本文链接:https://www.haomeiwen.com/subject/wcxjkctx.html