LeetCode Problem

859. Buddy Strings Link to LeetCode Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false. Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j]. For example, swapping at indices 0 and 2 in "abcd" results in "cbad". Example 1: Input: s = "ab", goal = "ba" Output: true Explanation: You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal. Example 2: Input: s = "ab", goal = "ab" Output: false Explanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal. class Solution { public boolean buddyStrings(String a, String b) { if(a == null || b == null || a.length() != b.length() || a.length() < 2 ) { return false; } int index1 = -1,index2 = -1; for (int i=0; i< a.length(); i++) { if (a.charAt(i) != b.charAt(i)) { if (index1 == -1) { index1 = i; } else if (index2 == -1) { index2 = i; } else { return false; } } } if (index1 == -1 && index2 == -1) { return hasDuplicate(a); } else if (index1 == -1 || index2 == -1) { return false; } return a.charAt(index1) == b.charAt(index2) && a.charAt(index2) == b.charAt(index1); } // in case: a="gool", b="gool", duplicate oo can be swapped private boolean hasDuplicate(String a) { Set< Character> set = new HashSet<>(); for (int i=0; i< a.length(); i++) { if (!set.add(a.charAt(i))) { return true; } } return false; } }