Leetcode 1417. Reformat The String
The problem is to reformat a given string so that no two adjacent characters are of the same type. Specifically, the string consists of lowercase alphabetic characters and digits. We need to rearrange the characters such that letters and digits alternate. If it is impossible to rearrange the string in this fashion, return an empty string.
s = "a0b1c2"
Output: "0a1b2c"
s = "leetcode"
Output: ""
(since there are no digits)s = "1229857369"
Output: ""
(since there are no letters)s = "covid2019"
Output: "c2o0v1i9d"
#include <string>
#include <vector>
#include <algorithm>
std::string reformat(std::string s) {
std::vector<char> letters, digits;
// Separate the characters into letters and digits
for (char c : s) {
if (std::isalpha(c)) {
letters.push_back(c);
} else {
digits.push_back(c);
}
}
// Check if reformatting is possible
if (std::abs((int)(letters.size() - digits.size())) > 1) {
return "";
}
// Resultant reformatted string
std::string result;
result.reserve(s.length());
// Determine which type to start with
bool lettersFirst = letters.size() > digits.size();
// Alternate characters
auto lit = letters.begin();
auto dit = digits.begin();
while (lit != letters.end() || dit != digits.end()) {
if (lettersFirst && lit != letters.end()) {
result.push_back(*lit++);
}
if (!lettersFirst && dit != digits.end()) {
result.push_back(*dit++);
}
lettersFirst = !lettersFirst;
}
return result;
}
n
is the length of the input string. This complexity arises because we are making two passes over the string (one for separating characters and one for building the final result).By following this strategy and utilizing efficient separation and alternating logic, we ensure the solution is both clear and optimal.
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?