当前位置:网站首页>力扣解法汇总821-字符的最短距离
力扣解法汇总821-字符的最短距离
2022-06-12 02:04:00 【失落夏天】
目录链接:
力扣编程题-解法汇总_分享+记录-CSDN博客
GitHub同步刷题项目:
https://github.com/September26/java-algorithms
原题链接:力扣
描述:
给你一个字符串 s 和一个字符 c ,且 c 是 s 中出现过的字符。
返回一个整数数组 answer ,其中 answer.length == s.length 且 answer[i] 是 s 中从下标 i 到离它 最近 的字符 c 的 距离 。
两个下标 i 和 j 之间的 距离 为 abs(i - j) ,其中 abs 是绝对值函数。
示例 1:
输入:s = "loveleetcode", c = "e"
输出:[3,2,1,0,1,0,0,1,2,2,1,0]
解释:字符 'e' 出现在下标 3、5、6 和 11 处(下标从 0 开始计数)。
距下标 0 最近的 'e' 出现在下标 3 ,所以距离为 abs(0 - 3) = 3 。
距下标 1 最近的 'e' 出现在下标 3 ,所以距离为 abs(1 - 3) = 2 。
对于下标 4 ,出现在下标 3 和下标 5 处的 'e' 都离它最近,但距离是一样的 abs(4 - 3) == abs(4 - 5) = 1 。
距下标 8 最近的 'e' 出现在下标 6 ,所以距离为 abs(8 - 6) = 2 。
示例 2:
输入:s = "aaab", c = "b"
输出:[3,2,1,0]
提示:
1 <= s.length <= 104
s[i] 和 c 均为小写英文字母
题目数据保证 c 在 s 中至少出现一次
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-distance-to-a-character
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:
代码:
public class Solution821 {
public int[] shortestToChar(String s, char c) {
List<Integer> list = new ArrayList<>();
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
char aChar = chars[i];
if (aChar == c) {
list.add(i);
}
}
int index = 0;
int[] result = new int[chars.length];
for (int i = 0; i < chars.length; i++) {
int leftIndex = list.get(index);
int rightIndex;
if (index >= list.size() - 1) {
rightIndex = leftIndex;
} else {
rightIndex = list.get(index + 1);
}
int abs = Math.abs(leftIndex - i);
int abs2 = Math.abs(rightIndex - i);
result[i] = Math.min(abs, abs2);
if (abs2 < abs) {
index++;
}
}
return result;
}
}边栏推荐
- Google 搜索广告系列设置前有哪些准备工作?
- Linux(CentOS7)安装MySQL-5.7版本
- 关于vagrant up的一个终结之谜
- [learn FPGA programming from scratch -19]: quick start chapter - operation steps 4-1- Verilog software download and construction of development environment - Altera quartz II version
- Data system provider Jidao technology joins dragon lizard community
- 如何最大化的利用各种匹配方式? ——Google SEM
- Redis实现消息队列的4种方案
- How to maximize the use of various matching methods—— Google SEM
- [adjustment] notice on the opening of the 2022 pre adjustment system for postgraduate enrollment of Shanghai Second University of Technology
- Leetcode 45 jump game II
猜你喜欢
随机推荐
Subject knowledge and educational ability of information technology in the first half of 2019 – subjective questions
How to maximize the use of various matching methods—— Google SEM
力扣解法汇总473-火柴拼正方形
PHP builds a high-performance API architecture based on sw-x framework (III)
初探性能优化!从2个月到4小时的性能提升!
小程序111111
竞价广告每次点击出价多少钱是固定的吗?
Lua function
Redis实现消息队列的4种方案
Linux(CentOS6)安装MySQL5.5版本数据库
C language programming classic games - minesweeping
Operating mechanism of Google ads bidding
MySQL高级部分知识点
SQL calculates KS, AUC, IV, psi and other risk control model indicators
入手Ticwatch2
Pyinstaller packaging Exe (detailed tutorial)
Ce soir - là, j'ai battu mon collègue...
联调这夜,我把同事打了...
Is the bidding price fixed for each click?
BaseDexClassLoader那些事









