原题链接:. - 力扣(LeetCode)
一开始没想太多,把每一种情况的边界确定后就开始了模拟:
int addMinimum(char * word){
char dic[3]={'a','b','c'};//存字典
int i=0,start=0,res=0;
int n=strlen(word);
while(start<n){
if(dic[i%3]==word[start]){//当前想要的字母与word字母相同
i++;
start++;
}
else if(dic[i%3]=='a'){
if(word[start]=='b'){
i++;
res++;
}
else{
res+=2;
i+=2;
}
}
else if(dic[i%3]=='b'){
if(word[start]=='a'){
res+=2;
i+=2;
}
else{
res++;
i++;
}
}
else{
i++;
res++;
}
}
return res+'c'-word[start-1];
}
写完后发现太繁琐,应该有更好的方法,仔细阅读代码发现,其实无疑就两种情况:
1.当前word[i]大于word[i-1],则这两个字母应该在同一个‘abc’中
2.当前word[i]小于word[i-1],则这两个字母在不同'abc'中
int addMinimum(char * word) {
int len = strlen(word);
int res = 0;
for (int i = 1; i < len; i++) {
res+=(word[i]-word[i-1]+2)%3;//实际把各类模拟都包括进去
}
return res+word[0]+2-word[len-1];//头尾两个单独处理
}