821. Shortest Distance to a Character
Easy
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:
Sstring length is in[1, 10000].Cis a single character, and guaranteed to be in stringS.- All letters in
SandCare lowercase.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Solution { public int[] shortestToChar(String S, char C) { int len = S.length(); int[] ret = new int[len]; int e = -1; for(int i=0; i<len; ++i) { if(S.charAt(i)==C) e = i; if(e==-1) ret[i] = len; else ret[i] = i-e; } e = len; for(int i=len-1; i>=0; --i) { if(S.charAt(i)==C) e = i; if(e<len) ret[i] = Math.min(ret[i], e-i); } return ret; } } |
No comments:
Post a Comment