1

题目

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<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;
    }
}

liuqinh2s
42 声望13 粉丝

认真写代码,搞创作