題目
給定一個字符串 S 和一個字符 C。返回一個代表字符串 S 中每個字符到字符串 S 中的字符 C 的最短距離的數(shù)組妥衣。
示例 1:
輸入: S = "loveleetcode", C = 'e'
輸出: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
說明:
字符串 S 的長度范圍為 [1, 10000]塘慕。
C 是一個單字符筋夏,且保證是字符串 S 里的字符。
S 和 C 中的所有字母均為小寫字母图呢。
解題思路
遍歷字符串条篷,以每個字符為中心骗随,同時對比左右兩邊的字符是否相等于目標字符串。
C++解法
#include <iostream>
#include <vector>
#include <map>
using namespace std;
class Solution {
public:
vector<int> shortestToChar(string S, char C) {
vector<int> vector;
for (int i = 0; i < S.size(); i++) {
int j = 0;
while (true) {
int before_index = i - j;
int after_index = i + j;
if (before_index >= 0 || after_index < S.size()) {
bool matched = (before_index >= 0 && S[before_index] == C) || (after_index < S.size() && S[after_index] == C);
if (matched) {
vector.push_back(j);
break;
} else {
j++;
}
} else {
vector.push_back(-1);
break;
}
}
}
return vector;
}
};
int main(int argc, const char * argv[]) {
// insert code here...
string S = "loveleetcode";
char C = 'e';
Solution solution;
vector<int> vector = solution.shortestToChar(S, C);
for (auto i: vector) {
cout << i << " ";
}
cout << endl;
return 0;
}
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/shortest-distance-to-a-character
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有赴叹。商業(yè)轉(zhuǎn)載請聯(lián)系官方授權(quán)鸿染,非商業(yè)轉(zhuǎn)載請注明出處。