# How to Calculate Buddy Strings in Java

## The challenge

Given two strings `A` and `B` of lowercase letters, return `true` if you can swap two letters in `A` so the result is equal to `B`, 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 `A[i]` and `A[j]`. For example, swapping at indices `0` and `2` in `"abcd"` results in `"cbad"`.

Example 1:

```Input: A = "ab", B = "ba"
Output: true
Explanation: You can swap A[0] = 'a' and A[1] = 'b' to get "ba", which is equal to B.```

Example 2:

```Input: A = "ab", B = "ab"
Output: false
Explanation: The only letters you can swap are A[0] = 'a' and A[1] = 'b', which results in "ba" != B.
```

Example 3:

```Input: A = "aa", B = "aa"
Output: true
Explanation: You can swap A[0] = 'a' and A[1] = 'a' to get "aa", which is equal to B.```

Example 4:

```Input: A = "aaaaaaabc", B = "aaaaaaacb"
Output: true
```

Example 5:

```Input: A = "", B = "aa"
Output: false```

Constraints:

• `0 <= A.length <= 20000`
• `0 <= B.length <= 20000`
• `A` and `B` consist of lowercase letters.

## The solution in Java code

```.wp-block-code{border:0;padding:0}.wp-block-code>div{overflow:auto}.shcb-language{border:0;clip:rect(1px,1px,1px,1px);-webkit-clip-path:inset(50%);clip-path:inset(50%);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;word-wrap:normal;word-break:normal}.hljs{box-sizing:border-box}.hljs.shcb-code-table{display:table;width:100%}.hljs.shcb-code-table>.shcb-loc{color:inherit;display:table-row;width:100%}.hljs.shcb-code-table .shcb-loc>span{display:table-cell}.wp-block-code code.hljs:not(.shcb-wrap-lines){white-space:pre}.wp-block-code code.hljs.shcb-wrap-lines{white-space:pre-wrap}.hljs.shcb-line-numbers{border-spacing:0;counter-reset:line}.hljs.shcb-line-numbers>.shcb-loc{counter-increment:line}.hljs.shcb-line-numbers .shcb-loc>span{padding-left:.75em}.hljs.shcb-line-numbers .shcb-loc::before{border-right:1px solid #ddd;content:counter(line);display:table-cell;padding:0 .75em;text-align:right;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;white-space:nowrap;width:1%}```class Solution {
public boolean buddyStrings(String A, String B) {
if (A.length() != B.length() || A.isEmpty()) return false;

if (!A.equals(B)) {
int count = 0;
char first = 'a', second = 'a';
for (int i = 0; i < A.length(); i++) {
if (A.charAt(i) == B.charAt(i)) continue;
if (count >= 2) return false;
if (count == 0) {
first = A.charAt(i);
second = B.charAt(i);
count++;
continue;
}
if (A.charAt(i) != second || B.charAt(i) != first) return false;
count++;
}
return count == 2;
}

if (A.length() > 26) return true;
int [] fre = new int[26];
for (char c : A.toCharArray()) {
if (fre[c-'a'] == 1) return true;
fre[c-'a']++;
}
return false;
}
}
```Code language: Java (java)```
Tags:
Subscribe
Notify of