Leetcode 821. 字符的最短距离

文章目录


给你一个字符串 s 和一个字符 c ,且 c 是 s 中出现过的字符。

返回一个整数数组 answer ,其中 answer.length == s.length 且 answer[i] 是 s 中从下标 i 到离它 最近 的字符 c 的 距离 。

两个下标 i 和 j 之间的 距离 为 abs(i - j) ,其中 abs 是绝对值函数。
在这里插入图片描述

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


简单便利

在这里插入图片描述

class Solution {
    
    
    public int[] shortestToChar(String s, char c) {
    
    


        //双指针每次右移确定范围,到双指针边界了就再次右移

        int[] end=new int[s.length()];

        //字符遍历
        for(int i=0;i<s.length();++i){
    
    
            //找左
            int left=i;
            for(;left>-1 && s.charAt(left)!=c;--left);
            if(left==-1 && s.charAt(0)!=c){
    
    
                left=-9999999;
            }


            //找右
            int right=i;
            for(;right<s.length() && s.charAt(right)!=c;++right);
            if(right==s.length() && s.charAt(s.length()-1)!=c){
    
    
                right=9999999;
            }


            //比较
            int num1=i-left;
            int num2=right-i;
            int num=Math.min(num1,num2);
            end[i]=num;
            
            
            
        }


        
        return end;














    }
}

猜你喜欢

转载自blog.csdn.net/qq_44627608/article/details/124267607