Leetcode 3210. Find the Encrypted String
Given a string s
, perform the following operation until the string becomes empty: remove the character at the position with the highest alphabetical value. If there are multiple such characters, remove the leftmost one. After each removal, append the removed character to a result string. The task is to return the resulting string after applying the above operations.
s = "abacad"
"dbcaab"
s
is not empty:
s
.erase
to remove the character from the string.O(n)
.O(n)
in the worst case since string elements need to be shifted.n
times (where n
is the length of the string), the overall time complexity is O(n^2)
.#include <iostream>
#include <string>
std::string findEncryptedString(const std::string &input) {
std::string s = input; // making a copy of input as we will modify it
std::string result;
while (!s.empty()) {
int maxPos = 0;
for (int i = 1; i < s.size(); ++i) {
if (s[i] > s[maxPos]) {
maxPos = i;
}
}
result.push_back(s[maxPos]);
s.erase(s.begin() + maxPos);
}
return result;
}
int main() {
std::string input = "abacad";
std::string output = findEncryptedString(input);
std::cout << "Encrypted String: " << output << std::endl; // Output should be "dbcaab"
return 0;
}
s
to a mutable string.result
.s
is not empty.s
by comparing each character (tracked using maxPos
).result
.s
using erase
.This solution respects the requirements and ensures each character is processed according to the given rules. The provided example demonstrates the expected output correctly.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?