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.java

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.

題目地址code

講解

這個簡單題還花了我很多時間,主要是思緒有點混亂。這道題給個人收穫是,開始和終止條件要最早檢查,分支條件的順序是很是重要的,是邏輯的一部分。leetcode

這道題我先遍歷一遍數組,掃描出結點的位置,存入一個結點數組。而後再遍歷一遍數組,計算出結果集,同時使用一個指針記錄結點數組的讀取進度。get

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;
    }
}
相關文章
相關標籤/搜索