821. Shortest Distance to a Character
Problem:
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]
Analysis:
2次遍历。
1: 从左往右S里面的字符到C的最短距离。
2: 从右往左S里面的字符到C的最短距离。
distance[i], S.charAt(i) 到C的最短距离。
Solution:
class Solution { public int[] shortestToChar(String S, char C) { int len = S.length(); char[] chars = S.toCharArray(); int[] res = new int[len]; int pos = Integer.MIN_VALUE/2; for (int i = 0; i < len; i++) { if (S.charAt(i) == C) pos = i; res[i] = i - pos; } pos = Integer.MAX_VALUE/2; for (int i = len - 1; i >= 0; i--) { if (S.charAt(i) == C) pos = i; res[i] = Math.min(pos - i, res[i]); } return res; } }
评论
发表评论