165、字元的最短距離
阿新 • • 發佈:2019-01-08
題目描述:
給定一個字串 S 和一個字元 C。返回一個代表字串 S 中每個字元到字串 S 中的字元 C 的最短距離的陣列。
示例 1:
輸入: S = “loveleetcode”, C = ‘e’
輸出: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
說明:
字串 S 的長度範圍為 [1, 10000]。
C 是一個單字元,且保證是字串 S 裡的字元。
S 和 C 中的所有字母均為小寫字母。
我的程式碼
class Solution { public int[] shortestToChar(String S, char C) { int [] result = new int[S.length()]; List<Integer> temMap = new ArrayList<>(); for (int i = 0; i < S.length(); i++) { char tem = S.charAt(i); if(tem == C){ temMap.add(i); result[i] = 0; } } int index = 0; for (int i = 0; i < S.length(); i++) { if(S.charAt(i) != C){ if(index == 0){ result[i] = Math.abs(temMap.get(index) - i); }else { if(temMap.size() == index){ result[i] = Math.abs(temMap.get(index - 1) - i); }else result[i] = Math.min(Math.abs(temMap.get(index -1) - i), Math.abs(temMap.get(index) - i)); } }else { index ++; } } return result; } }