Skip to content

Latest commit

 

History

History
 
 

859. Buddy Strings

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B.

 

Example 1:

Input: A = "ab", B = "ba"
Output: true

Example 2:

Input: A = "ab", B = "ab"
Output: false

Example 3:

Input: A = "aa", B = "aa"
Output: true

Example 4:

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

Example 5:

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

 

Note:

  1. 0 <= A.length <= 20000
  2. 0 <= B.length <= 20000
  3. A and B consist only of lowercase letters.

Companies:
Google

Related Topics:
String

Solution 1.

// OJ: https://leetcode.com/problems/buddy-strings/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    bool buddyStrings(string A, string B) {
        if (A.size() != B.size()) return false;
        int cnts[26] = {0}, first = -1, second = -1;
        bool hasDup = false;
        for (int i = 0; i < A.size(); ++i) {
            if (++cnts[A[i] - 'a'] == 2) hasDup = true;
            if (A[i] == B[i]) continue;
            if (first == -1) first = i;
            else if (second == -1) second = i;
            else return false;
        }
        return (first != -1 && second != -1 && A[first] == B[second] && A[second] == B[first])
            || (first == -1 && second == -1 && hasDup);
    }
};