Skip to content

Commit

Permalink
June22: smallest beautiful string [H]
Browse files Browse the repository at this point in the history
Greedy, Time: O(N), Space: O(1): in-place update
  • Loading branch information
aucker committed Jun 22, 2024
1 parent 66eed04 commit 2c79e71
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
3 changes: 1 addition & 2 deletions daily/June21.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ class Solution {
*
* @param temperatureA
* @param temperatureB
* @return int
*/
* @return int */
int temperatureTrend(vector<int>& temperatureA, vector<int>& temperatureB) {
auto cmp = [](int x, int y) { return (x > y) - (x < y); };

Expand Down
37 changes: 37 additions & 0 deletions daily/June22.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
/**
* @brief LC: 2663: Lexicographically Smallest Beautiful string
* Greedy algorithm
* Time: O(N), N: len(s), Space: O(1), inplace update
*
* @param s
* @param k
* @return string
*/
string smallestBeautifulString(string s, int k) {
k += 'a';
int n = s.length();
int i = n - 1; // start from last letter

s[i]++;
while (i < n) {
if (s[i] == k) { // go upgrade
if (i == 0) { // can't go upgrade
return "";
}
// go upgrade
s[i] = 'a';
s[--i]++;
} else if (i && s[i] == s[i - 1] || i > 1 && s[i] == s[i - 2]) {
s[i]++; // if s[i] form the
} else {
i++; // check the latter
}
}
return s;
}
};

0 comments on commit 2c79e71

Please sign in to comment.