2663. 字典序最小的美丽字符串
题目链接:2663. 字典序最小的美丽字符串
代码如下:
//贪心算法
//参考链接:https://leetcode.cn/problems/lexicographically-smallest-beautiful-string/solutions/2251229/tan-xin-pythonjavacgo-by-endlesscheng-yix5
class Solution
{
public:string smallestBeautifulString(string s, int k) {k+='a';int n=s.size();int i=n-1;//从最后一个字母开始s[i]++;//先加1while(i<n){if(s[i]==k)//需要进位{//无法进位if(i==0) {return "";}//进位s[i]='a';s[--i]++;}else if(i&&s[i]==s[i-1]||i>1&&s[i]==s[i-2]){s[i]++;//如果s[i]和左侧的字符形成回文串,就继续增加s[i]}else {i++;}//反过来检查后面是否有回文串}return s;}
};