【LeetCode-字符串】亲密字符串

题目描述

给定两个由小写字母构成的字符串 A 和 B ,只要我们可以通过交换 A 中的两个字母得到与 B 相等的结果,就返回 true ;否则返回 false 。
示例:

输入: A = "ab", B = "ba"
输出: true

输入: A = "ab", B = "ab"
输出: false

输入: A = "aa", B = "aa"
输出: true

题目链接: https://leetcode-cn.com/problems/buddy-strings/

思路

遍历字符串 A,记录 A 和 B 字符不相同的位置(下标),将下标放进数组 index 中。因为只交换两个字母,所以 index 的长度要为 2 或者为 0.

  • index.size()==2:
    判断 A[index[0]] 和 B[index[1]] 是否相等以及 A[index[1]] 和 B[index[0]] 是否相等。如果相等返回 true;
  • index.size()==0:
    说明 A 和 B 是相同的字符串。在示例中,"ab" 和 "ab" 返回 false,而 "aa" 和 "aa" 返回 true。所以,我们判断字符串 A 中有没有重复的字符,有的话返回 true。
  • 其余情况返回 false。

代码如下:

class Solution {
public:
    bool buddyStrings(string A, string B) {
        if(A.size()!=B.size()) return false;

        vector<int> index;
        for(int i=0; i<A.size(); i++){
            if(A[i]!=B[i]) index.push_back(i);
        }
        if(index.size()==2 && A[index[0]]==B[index[1]] && A[index[1]]==B[index[0]]) return true;
        if(index.size()==0){
            unordered_set<char> s;
            for(int i=0; i<A.size(); i++){
                if(s.count(A[i])!=0) return true;
                else s.insert(A[i]);
            }
        }
        return false;
    }
};
  • 时间复杂度:O(n)
  • 空间复杂度:O(n)
原文地址:https://www.cnblogs.com/flix/p/13493049.html