题目
代码部分(Python 92ms 73.32%)
class Solution:
def shortestToChar(self, S: str, C: str) -> List[int]:
res = []
for i in range(len(S)):
if S[i] is C:
res.append(0)
continue
l = i - 1
r = i + 1
while True:
if (l >= 0 and S[l] == C):
res.append(i - l)
break
if (r < len(S) and S[r] == C):
res.append(r - i)
break
l -= 1
r += 1
return res;
代码部分(Java 2ms 97.80%)
class Solution {
public int[] shortestToChar(String S, char C) {
char[] ch = S.toCharArray();
int len = ch.length;
int[] res = new int[len];
for(int i = 0; i < len; i++){
if(ch[i] == C){
res[i] = 0;
continue;
}
int l = i - 1;
int r = i + 1;
while(true){
if(l >= 0 && ch[l] == C){
res[i] = i - l;
break;
}
if(r < len && ch[r] == C){
res[i] = r - i;
break;
}
l--;
r++;
}
}
return res;
}
}