本文主要是介绍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]
思路:扫两遍, O(N),第一遍从左往右,用i - pos来算到左边的C的最短距离
扫描完后,从右往左扫,算到右边C的最短距离,两个取最小值就是答案;
注意pos initial = -n;
class Solution {public int[] shortestToChar(String S, char C) {if(S == null || S.length() == 0) {return new int[0];}int n = S.length();int[] res = new int[n];int pos = -n;for(int i = 0; i < n; i++) {char sc = S.charAt(i);if(sc == C) {pos = i;}res[i] = i - pos;}// 循环完后,pos代表最后一个C的位置;for(int i = n - 1; i >= 0; i--) {char sc = S.charAt(i);if(sc == C) {pos = i;}res[i] = Math.min(res[i], Math.abs(i - pos));}return res;}
}
这篇关于Shortest Distance to a Character的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!