Leetcode 2716. Minimize String Length
You are given a string s
consisting of lowercase English letters. Your task is to minimize the length of the string by performing the following operation any number of times:
Find the minimum possible length of the resulting string after performing the above operation any number of times.
Assuming typical problem constraints:
We can use a stack-based approach to solve this problem. The key insight is that if two adjacent characters in the string are the same, they will cancel each other out. Using a stack, we can efficiently process and remove these adjacent pairs:
The length of the stack at the end gives the desired minimized string length.
Here is the solution in C++:
#include <iostream>
#include <string>
#include <stack>
int minimizeStringLength(const std::string& s) {
std::stack<char> stack;
for (char c : s) {
if (!stack.empty() && stack.top() == c) {
stack.pop(); // Remove the pair of adjacent equal characters
} else {
stack.push(c); // Push the current character onto the stack
}
}
return stack.size();
}
int main() {
std::string s;
std::cout << "Enter the string: ";
std::cin >> s;
int result = minimizeStringLength(s);
std::cout << "The minimized string length is: " << result << std::endl;
return 0;
}
This code includes a main function for testing, where you can enter the string, and it will print out the minimized length. The minimizeStringLength
function implements the stack-based approach to solving the problem.
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?