【LeetCode】 821. 字元的最短距離
阿新 • • 發佈:2018-11-08
Vector向量的應用
1. 題目介紹
題目
給定一個字串 S 和一個字元 C。返回一個代表字串 S 中每個字元到字串 S 中的字元 C 的最短距離的陣列。
示例 1:
輸入: S = “loveleetcode”, C = ‘e’
輸出: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
說明:
1.字串 S 的長度範圍為 [1, 10000]。
2.C 是一個單字元,且保證是字串 S 裡的字元。
3.S 和 C 中的所有字母均為小寫字母。
2. 思路分析
利用vector向量將距離存入向量中,再將向量返回
3. 程式碼
//C++
#include < iostream>
#include <vector>
#include <cmath>
using namespace std;
vector<int> shortestToChar(string S, char C) {
int len=S.length();
vector<int>dis(len);
for(int i=0;i<len;i++){
for(int j=i;j<len;j++){
if(S[j]==C){
dis[i]=abs(j-i);
break ;
}
if(j==len-1){ //當後面沒有的情況
dis[i]=len;
}
}
for(int j=i;j>=0;j--){
if(S[j]==C){
dis[i]=min(abs(j-i),dis[i]);
break;
}
}
}
vector<int>::iterator t ;//向量的遍歷輸出
for(t=dis.begin(); t!=dis.end()-1; t++)
cout<<*t<<",";
cout<< *t<<endl;
return dis;
}
int main(){
string S="loveleetcode";
char C='e';
shortestToChar(S,C);
return 0;
}
參考執行8ms的演算法
class Solution
{
public:
vector<int> shortestToChar(string S, char C)
{
int N = S.length();
vector<int> vDistances(N, N);
for ( int d = N, i = 0; i < N; ++i )
{
d = (C == S[i] ? 0 : d+1);
//vDistances[i] = min(vDistances[i], d);
vDistances[i] = d;
}
for ( int d = N, i = N-1; i >= 0; --i )
{
d = (C == S[i] ? 0 : d+1);
vDistances[i] = min(vDistances[i], d);
}
return std::move(vDistances);
}
};