LeetCode 1790: Check if One String Swap Can Make Strings Equal Solution
Master LeetCode problem 1790 (Check if One String Swap Can Make Strings Equal), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1790. Check if One String Swap Can Make Strings Equal
Problem Explanation
Explanation:
To solve this problem, we can follow these steps:
- Check if the two strings are already equal. If they are, return true.
- Iterate through both strings simultaneously and keep track of the characters that differ at the same index.
- If there are more than two differing characters or the differing characters are not the same when swapped, return false.
- If there are exactly two differing characters and they can be swapped to make the strings equal, return true.
Time Complexity:
The time complexity of this approach is O(n), where n is the length of the input strings.
Space Complexity:
The space complexity of this approach is O(1) as we are not using any extra space.
Solutions:
Solution Code
class Solution {
public boolean areAlmostEqual(String s1, String s2) {
if (s1.equals(s2)) {
return true;
}
int n = s1.length();
int diffCount = 0;
int[] diffIndexes = new int[2];
for (int i = 0; i < n; i++) {
if (s1.charAt(i) != s2.charAt(i)) {
diffIndexes[diffCount] = i;
diffCount++;
if (diffCount > 2) {
return false;
}
}
}
return (diffCount == 2 && s1.charAt(diffIndexes[0]) == s2.charAt(diffIndexes[1]) &&
s1.charAt(diffIndexes[1]) == s2.charAt(diffIndexes[0]));
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1790 (Check if One String Swap Can Make Strings Equal)?
This page provides optimized solutions for LeetCode problem 1790 (Check if One String Swap Can Make Strings Equal) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1790 (Check if One String Swap Can Make Strings Equal)?
The time complexity for LeetCode 1790 (Check if One String Swap Can Make Strings Equal) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1790 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1790 in Java, C++, or Python.