Length Check: First, check if the lengths of the two strings are different. If they are, return false because it’s impossible to make them equal through any number of swaps.
Immediate Match: If the two strings are already equal, check if there are at least two duplicate characters in s. This would allow us to swap two identical characters in s, thereby preserving its equality with goal.
Identify Swap Position: If the strings are not equal, identify the positions where the characters differ. If there are exactly two differences, check if swapping these two characters in s makes it equal to goal.
Conclusion: Return true if the conditions are met, otherwise return false.
publicclassSolution {
publicbooleanbuddyStrings(String s, String goal) {
if (s.length() != goal.length()) {
returnfalse;
}
if (s.equals(goal)) {
// Check if there is at least one character that appears twiceint[] count =newint[26];
for (char c: s.toCharArray()) {
count[c -'a']++;
if (count[c -'a']> 1) {
returntrue;
}
}
returnfalse;
}
int first =-1, second =-1;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != goal.charAt(i)) {
if (first ==-1) {
first = i;
} elseif (second ==-1) {
second = i;
} else {
// More than two differencesreturnfalse;
}
}
}
return (second !=-1 && s.charAt(first) == goal.charAt(second) && s.charAt(second) == goal.charAt(first));
}
}
publicclassSolution {
publicbooleanbuddyStrings(String s, String goal) {
if (s.length() != goal.length()) {
returnfalse;
}
if (s.equals(goal)) {
// Check if there is at least one character that appears twice Set<Character> sChars =new HashSet<>();
for (char c: s.toCharArray()) {
if (!sChars.add(c)) {
returntrue;
}
}
returnfalse;
}
int first =-1, second =-1;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != goal.charAt(i)) {
if (first ==-1) {
first = i;
} elseif (second ==-1) {
second = i;
} else {
// More than two differencesreturnfalse;
}
}
}
return (second !=-1 && s.charAt(first) == goal.charAt(second) && s.charAt(second) == goal.charAt(first));
}
}
publicclassSolution {
publicbooleanbuddyStrings(String s, String goal) {
if (s.length() != goal.length()) {
returnfalse;
}
Set<Character> sChars =new HashSet<>();
int first =-1, second =-1;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
char d = goal.charAt(i);
if (c != d) {
if (first ==-1) {
first = i;
} elseif (second ==-1) {
second = i;
} else {
// More than two differencesreturnfalse;
}
}
sChars.add(c);
}
if (first !=-1 && second !=-1) {
return s.charAt(first) == goal.charAt(second) && s.charAt(second) == goal.charAt(first));
}
if (first !=-1) {
returnfalse; // Only have 1 different place }
return sChars.size() < s.length(); // No different between s & goal, check if A contains at least 1 duplicate letters. }
}