1.题目描述数组
给定一个字符串 S
和一个字符 C
。返回一个表明字符串 S
中每一个字符到字符串 S
中的字符 C
的最短距离的数组。spa
示例 1:code
输入: S = "loveleetcode", C = 'e' 输出: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
说明:blog
S
的长度范围为 [1, 10000]
。C
是一个单字符,且保证是字符串 S
里的字符。S
和 C
中的全部字母均为小写字母。2.解决方法leetcode
class Solution { public: vector<int> shortestToChar(string S, char C) { vector<int> res; vector<int> con; int l=0; int k=0; int Size=S.size(); int cs=0; for(int i=0;i<S.size();i++) { int tem=S.find(C,i); if(tem!=-1) {con.push_back(tem); i=tem; } } cs=con.size(); while(1) { if(k<=con[l]&&l==0) { res.push_back(con[l]-k); k++; } else if(k<=con[l]&&l>=1) { int m=min(con[l]-k,k-con[l-1]); res.push_back(m); k++; } else if(k>con[l]&&l==cs-1) { res.push_back(k-con[l]); k++; } else { l++; } if(k==Size) return res; } } };