题解 {2663. 字典序最小的美丽字符串}
LINK: https://leetcode.cn/problems/lexicographically-smallest-beautiful-string/submissions/
;
关于回文串的性质:
.
对于任何子串都不是回文串的字符串 s = [abcdef]
此时要在尾部添加一个字符 即abcdef X
, 那么只要保证
X
≠
f
∧
X
≠
e
X \neq f \land X \neq e
X=f∧X=e, 那么 新的字符串 他的任何子串 也都不是回文的;
从后往前遍历i = [n-1, ..., 0]
, 让s[i]
递增 即a,b,c,d,...
, 一旦s[i]
满足条件 (即!= s[i-1]
且!= s[i-2]
) 比如当前是s1 s2 s[i] s3 s4 s5 ...
只要
K
≠
3
K\neq 3
K=3 那么对于s3, s4, s5, ...
这些元素 一定是有解的, 同样要满足s3 != {s2, s[i]}, s4 != {s[i], s3}, ...
;
@DELIMITER
代码;
string smallestBeautifulString(string S, int K) {
int n = S.size();
char ma = 'a' + K - 1;
bool succ = false;
auto Valid = [&]( int _i){
if( _i - 1 >= 0 && S[ _i] == S[ _i - 1]) return false;
if( _i - 2 >= 0 && S[ _i] == S[ _i - 2]) return false;
return true;
};
for( int i = n - 1; i >= 0; --i){
while( S[ i] < ma){
++ S[ i];
if( Valid( i)){
for( int j = i + 1; j < n; ++j){
S[ j] = 'a' - 1;
while( S[ j] < ma){
++ S[ j];
if( Valid( j)){ break;}
}
ASSERT_( Valid( j));
}
return S;
}
}
}
return "";
}