Posted on

Description

Submission

class Solution {
public:
    bool buddyStrings(string s, string goal) {
        
        if(s.length() != goal.length()) {
            return false;
        }

        int n = s.length();

        bool flag = false;
        vector<int> cnt1(26, 0);
        vector<int> cnt2(26, 0);
        for(int i = 0; i < n; ++i) {
            int t1 = s[i] - 'a';
            int t2 = goal[i] - 'a';
            ++cnt1[t1];
            ++cnt2[t2];
            if(cnt1[t1] == 2) flag = true; 
        }

        for(int i = 0; i < 26; ++i) {
            if(cnt1[i] != cnt2[i]) return false;
        }

        if(s == goal) {
            return flag;
        }

        

        vector<int> indices;

        for(int i = 0; i < n; ++i) {
            if(goal[i] != s[i]) indices.push_back(i);
            if(indices.size() > 2) return false;
        }

        return indices.size() == 2;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *