Check if Strings Can be Made Equal With Operations I

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.
I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.
You are given two strings s1 and s2, both of length 4, consisting of lowercase English letters.
You can apply the following operation on any of the two strings any number of times:
- Choose any two indices
iandjsuch thatj - i = 2, then swap the two characters at those indices in the string.
Return true if you can make the strings s1 and s2 equal, and false otherwise.
LeetCode Problem - 2839
class Solution {
public boolean canBeEqual(String s1, String s2) {
// If the strings are already equal, return true
if (s1.equals(s2)) return true;
StringBuilder sb = new StringBuilder(s1);
boolean flag = true;
// Try swapping the characters at positions 0 and 2, and 1 and 3
for (int i = 0; i < 2; i++) {
flag = true;
char c1 = sb.charAt(i);
char c2 = sb.charAt(i + 2);
// Swap the characters
sb.setCharAt(i, c2);
sb.setCharAt(i + 2, c1);
// Check if the modified string equals s2
if (sb.toString().equals(s2)) {
flag = false;
return true;
}
}
// If the above swaps did not work, try swapping using the helper method
if (flag) {
for (int i = 0; i < 2; i++) {
boolean ans = swap(s1, s2, i);
if (ans) return true;
}
return false;
}
return false;
}
// Helper method to perform the swap operation
public boolean swap(String str1, String str2, int idx) {
StringBuilder sb = new StringBuilder(str1);
char c1 = sb.charAt(idx);
char c2 = sb.charAt(idx + 2);
// Swap the characters
sb.setCharAt(idx, c2);
sb.setCharAt(idx + 2, c1);
// Check if the modified string equals str2
return sb.toString().equals(str2);
}
}




