最新消息:XAMPP默认安装之后是很不安全的,我们只需要点击左方菜单的 "安全"选项,按照向导操作即可完成安全设置。

leetcode讲解–821. Shortest Distance to a Character

XAMPP相关 admin 1351浏览 0评论
 题目
Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string.

Example 1:

Input: S = “loveleetcode”, C = ‘e’
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
Note:

S string length is in [1, 10000].
C is a single character, and guaranteed to be in string S.
All letters in S and C are lowercase.
题目地址

讲解
这个简单题还花了我不少时间,主要是思绪有点混乱。这道题给我的收获是,开始和终止条件要最先检查,分支条件的顺序是非常重要的,是逻辑的一部分。

这道题我先遍历一遍数组,扫描出结点的位置,存入一个结点数组。然后再遍历一遍数组,计算出结果集,同时使用一个指针记录结点数组的读取进度。

Java代码
class Solution {
public int[] shortestToChar(String S, char C) {
char[] cc = S.toCharArray();
int[] result = new int[cc.length];
List<Integer> index = new ArrayList<>();
for(int i=0;i<cc.length;i++){
if(cc[i]==C){
index.add(i);
System.out.print(i);
}
}
int count=0;
for(int i=0;i<cc.length;i++){
if(i==index.get(count)){
if(count<index.size()-1){
count++;
}
result[i] = 0;
}else if(count==0 && i<index.get(count)){
result[i] = index.get(count)-i;
}else if(count==index.size()-1 && i>index.get(count)){
result[i] = i – index.get(count);
}else if(count>0){
if(i-index.get(count-1) < index.get(count)-i){
result[i] = i-index.get(count-1);
}else{
result[i] = index.get(count)-i;
}
}
}
return result;
}
}

转载请注明:XAMPP中文组官网 » leetcode讲解–821. Shortest Distance to a Character

您必须 登录 才能发表评论!