821. Shortest Distance to a Character
https://leetcode.com/problems/shortest-distance-to-a-character/solution/ // three pass, accepted class Solution { public int[] shortestToChar(String S, char C) { // left scan , update e's index // right scan , update e's index // if no char c found, yet, mark it as interger.max value // final scan, get min, return int n = S.length(); int[] left = new int[n]; int[] right = new int[n]; int charIndex = -1; // left scan for(int i = 0; i < n; i++){ if(S.charAt(i) == C){ charIndex = i; } if(charIndex < 0){ left[i] = Integer.MAX_VALUE; }else{ left[i] = i - charIndex; } } charIndex = -1; // reset // right scan for(int i = n - 1; i >= 0; i--){ if(S.charAt(i) == C){ charIndex = i; } if(charIndex < 0){ right[i] = Integer.MAX_VALUE; }else{ right[i] = charIndex - i; } } // get min for(int i = 0; i < n; i++){ left[i] = Math.min(left[i], right[i]); } return left; } } // two pass, accepted class Solution { public int[] shortestToChar(String S, char C) { // left scan , update e's index // right scan , update e's index // if no char c found, yet, mark it as interger.max value // final scan, get min, return int n = S.length(); int[] left = new int[n]; int[] right = new int[n]; int charIndex = -1; // left scan for(int i = 0; i < n; i++){ if(S.charAt(i) == C){ charIndex = i; } if(charIndex < 0){ left[i] = Integer.MAX_VALUE; }else{ left[i] = i - charIndex; } } charIndex = -1; // reset // right scan for(int i = n - 1; i >= 0; i--){ if(S.charAt(i) == C){ charIndex = i; } if(charIndex < 0){ right[i] = Integer.MAX_VALUE; }else{ right[i] = charIndex - i; } right[i] = Math.min(right[i], left[i]); } return right; } }
posted on 2018-11-08 16:10 猪猪🐷 阅读(106) 评论(0) 收藏 举报
浙公网安备 33010602011771号