Shortest Distance to a Character
扫两次, 用count记录非C的字符的个数, 这时候注意两边的corn case, 开始扫的时候要把count设置为MAX, 因为如果是0, 那么是意味着当前i的位置的字符是C. 所以要设置成MAX
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Solution { public int[] shortestToChar(String S, char C) { int[] res = new int[S.length()]; int count = Integer.MAX_VALUE / 2; for (int i = 0 ; i < S.length(); i++) { if(S.charAt(i) == C) { count = 0; } res[i] = count++; } count = Integer.MAX_VALUE / 2; for(int i = S.length() - 1; i >= 0; i--) { if(S.charAt(i) == C) { count = 0; } res[i] = Math.min(count++, res[i]); } return res; } } |