题目描述:
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]
Note:
S
string length is in[1, 10000].
C
is a single character, and guaranteed to be in stringS
.- All letters in
S
andC
are lowercase.
解题思路:
一直想有没有什么简便的方法,没想出来,就用了笨方法。
代码:
1 class Solution { 2 public: 3 vector shortestToChar(string S, char C) { 4 vector res; 5 for (int i = 0; i < S.size(); i++) { 6 if (S[i] == C) 7 index.push_back(i); 8 } 9 for (int i = 0; i < S.size(); ++i){10 int length = INT_MAX;11 if (S[i] == C) {12 res.push_back(0);13 continue;14 }15 for (int j = 0; j < index.size(); ++j) {16 if (abs(index[j] - i ) < length)17 length = abs(index[j] - i);18 else19 break;20 }21 res.push_back(length);22 }23 return res;24 25 }26 vector index;27 };
PS:
看了其他人的解法,有一方法很棒,分享下:
1 vector shortestToChar(const string& s, char c) { 2 int size = s.size(), lastLocation = -1; 3 vector ret (size, INT_MAX); 4 for (int i = 0; i < size; ++i) { 5 if (s[i] == c) lastLocation = i; 6 if (lastLocation != -1) ret[i] = i - lastLocation; 7 } 8 for (int i = lastLocation - 1; i >= 0; --i) { 9 if (s[i] == c) lastLocation = i;10 ret[i] = min(lastLocation - i, ret[i]);11 }12 return ret;13 }