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:
S
string length is in[1, 10000].
C
is a single character, and guaranteed to be in stringS
.- All letters in
S
andC
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 Subarray, Maximum Product Subarray, Best Time to Buy and Sell Stock, Product of Array Except Self, Daily Temperatures, Longest Mountain in Array, Max Chunks To Make Sorted, Max Chunks To Make Sorted II.