Leetcode 2839. Check if Strings Can be Made Equal With Operations I
Given two strings s1
and s2
, check if they can be made equal by performing some number of operations. In one operation, you can swap any two adjacent characters of s1
. Return true
if you can make s1
equal to s2
, and false
otherwise.
s1
and s2
?
s1
and s2
will be in the range [1, 1000]
and they are the same length.To determine if you can make s1
equal to s2
through adjacent swaps, it is equivalent to asking if s1
can be rearranged to become s2
. This is a fundamental property of permutations.
Our approach will involve:
Check if strings s1
and s2
have the same characters with the same frequency; this would confirm that one can be rearranged to be the other.
If they do, return true
; otherwise, return false
.
#include <algorithm>
#include <string>
bool canBeEqualWithOperations(std::string s1, std::string s2) {
// If lengths of s1 and s2 are different, they cannot be made equal
if (s1.length() != s2.length()) return false;
// Sort the strings
std::sort(s1.begin(), s1.end());
std::sort(s2.begin(), s2.end());
// Compare the sorted strings
return s1 == s2;
}
Input Check: We first check if the lengths of s1
and s2
are different. If they are, they cannot be made equal, and the function returns false
.
Sorting: The strings s1
and s2
are sorted. Sorting rearranges the characters in a specific order (usually lexicographical).
Comparison: After sorting, if s1
is identical to s2
, it means s1
can be rearranged to become s2
, so we return true
. Otherwise, return false
.
This solution ensures that we can determine the equality possibility of s1
and s2
through adjacent swaps efficiently.
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?