LeetCode 821. Shortest Distance to a Character

原题链接在这里:https://leetcode.com/problems/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.

题解:

The idea is find nearest C, it could be left or right.

Then we could calculate left distance and right distance and take smaller one.

First left side, if there is no left one, distance is defaulted to be maximum. Here it is i+n. n is the length of S.

Then right side, update the res with smaller distance.

Time Complexity: O(n). n = S.length().

Space: O(n). res space.

AC Java:

 1 class Solution {
 2     public int[] shortestToChar(String S, char C) {
 3         int n = S.length();
 4         int [] res = new int[n];
 5         int po = -n;
 6         for(int i = 0; i<n; i++){
 7             if(S.charAt(i) == C){
 8                 po = i;
 9             }
10             
11             res[i] = i-po;
12         }
13         
14         for(int i = n-1; i>=0; i--){
15             if(S.charAt(i) == C){
16                 po = i;
17             }
18             
19             res[i] = Math.min(res[i], Math.abs(po-i));
20         }
21         
22         return res;
23     }
24 }

类似One or two passes from left to right/right to left. Maximum SubarrayMaximum Product SubarrayBest Time to Buy and Sell StockProduct of Array Except SelfDaily TemperaturesLongest Mountain in ArrayMax Chunks To Make SortedMax Chunks To Make Sorted II.

跟上Push Dominoes.

posted @ 2019-08-17 11:12  Dylan_Java_NYC  阅读(331)  评论(0编辑  收藏  举报