題目地址:
https://leetcode.com/problems/shortest-distance-to-a-character/
給定一個字符串和一個中字母,要求返回一個數組,其中等於與與其距離最近的那個的距離。
由於距離最近的要麼在其左邊要麼在其右邊,所以可以用遍歷兩遍的方式,從左到右一遍,從右到左一遍,每次遍歷用一個變量記錄最新出現的的位置,同時更新最短距離。代碼如下:
public class Solution {
public int[] shortestToChar(String S, char C) {
if (S == null || S.isEmpty()) {
return new int[0];
}
int[] res = new int[S.length()];
// 先從左向右遍歷,並計算每個字符與其最近的左邊的C的距離。
// 由於有可能左邊並不存在字符C,所以要先設pos爲一個值,
// 使得res[i]先取到一個大到不可能正確的值,後面一輪遍歷的時候再更新成正確的值
int pos = -S.length();
for (int i = 0; i < S.length(); i++) {
if (S.charAt(i) == C) {
pos = i;
}
res[i] = i - pos;
}
// 接下來從右向左遍歷,並計算每個字符與其最近的左邊的C的距離。
pos = S.length() * 2 - 1;
for (int i = S.length() - 1; i >= 0; i--) {
if (S.charAt(i) == C) {
pos = i;
}
res[i] = Math.min(res[i], pos - i);
}
return res;
}
}
時間複雜度,空間。