Leetcode 2810. Faulty Keyboard
You are given a string s
that represents the text typed into a faulty keyboard where certain keys are “stuck”. Specifically, any character that appears consecutively more than once should be treated as if it was typed only once. Return the final string after removing consecutive duplicates.
Before proceeding with the solution, let’s clarify some essential points:
s
?Assuming comparison is case-sensitive and given no specific constraints:
#include <iostream>
#include <string>
std::string removeFaultyKeys(const std::string& s) {
if (s.empty()) return "";
std::string result;
result.reserve(s.size()); // Reserve space to avoid multiple reallocations
char lastChar = '\0';
for (char c : s) {
if (c != lastChar) {
result += c;
lastChar = c;
}
}
return result;
}
int main() {
std::string input;
std::cout << "Enter the string typed on the faulty keyboard: ";
std::getline(std::cin, input);
std::string output = removeFaultyKeys(input);
std::cout << "Corrected string: " << output << std::endl;
return 0;
}
The time complexity of the solution is O(n), where n
is the length of the input string s
. We are iterating through the string once and performing constant-time checks and operations for each character.
lastChar
variable to keep track of the last added character.lastChar
.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?