int closetTarget(char**words,int wordsSize,char*target,int startIndex){
if(strcmp(target,words[startIndex])==0)//若目标和给定位置的字符相同返回0
return 0;
int nextRight=startIndex;
int nextLeft =startIndex;
int count=0;
bool falg=false;
do{//判断字符串和target是否一致
if((strcmp(target,words[nextRight])==0)||strcmp(target,words[nextLeft])==0){
flag=true;
}else{
count++;
nextRight=(nextRight+1)%wordsSize;//向前移动
nextLeft=(nextLeft-1+wordsSize)%wordsSize;//向后移动
}
if(flag){//找到满足条件的字符串,跳出循环
break;
}
}while(nextRight!=startIndex);
if(nextRight==startIndex){//没有找到,返回-1
return -1;
}else{//找到,返回最短距离
return count;
}
}
class Solution{
public:
int takeCharacters(string s,int k){
int a=count(s.begin(),s.end(),'a'),b=count(s.begin(),s.end(),'b'),c=count(s.begin(),s.end(),'c'),n=s.size();//计算总数
if(a<k||b<k||c<k)
return -1;
a-=k,b-=k,c-=k;
vector<int>nums(3),check{a,b,c};//num记录abc的数目,check为上限
int ans=INT_MAX,i,j;
for(i=0,j=0;j<s.size();j++)//寻找滑动窗口的最大长度
{
nums[s[j]-'a']++;
if(nums[s[j]-'a']>check[s[j]-'a'])
{
while(nums[s[j]-'a']>check[s[j]-'a'])
{
nums[s[i]-'a']--;
i++;
}
}
ans=min(n-(j-i+1),ans);
}
return ans;
}
};