leetcode讲解--821. Shortest Distance to a Character

题目

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:

  1. S string length is in [1, 10000].
  2. C is a single character, and guaranteed to be in string S.
  3. 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 index = new ArrayList<>();
        for(int i=0;iindex.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;
    }
}

你可能感兴趣的:(leetcode,算法,数组)