Buddy Strings string

Description

859. Buddy Strings
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.
1
2
3

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.
1
2
3

Constraints:

1 <= s.length, goal.length <= 2 * 104
s and goal consist of lowercase letters.
1
2

Solution

#include <string>
using namespace std;

// @lc code=start
class Solution
{
public:
    bool buddyStrings(string s, string goal)
    {
        //if two strings have difference length
        if (s.size() != goal.size())
            return false;

        //to mark the occurences of 26 lowercase letters
        int count1[26] = {0};
        int count2[26] = {0};
        int sum = 0; //sum of different numbers

        //count occurences
        for (int i = 0; i < s.size(); ++i)
        {
            int a = s[i] - 'a';
            int b = goal[i] - 'a';
            count1[a]++;
            count2[b]++;
            if (a != b)
                sum++;
        }

        //check if has repeated letters and check if string s and string goal have same elements
        bool hasRepeats = false;
        for (int i = 0; i < 26; i++)
        {
            if (count1[i] != count2[i])
                return false;
            if (count1[i] > 1)
                hasRepeats = true;
        }

        //check if there're only two spots different(which means a swap can make them identical), or if all elements in both strings are the same and there're repeats of letters which means a swap will not change its equality
        return sum == 2 || (sum == 0 && hasRepeats);
    }
};
// @lc code=end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
Last Updated: 11/25/2021, 5:01:32 AM
Contributors: oddnaveed