首页 技术 正文
技术 2022年11月9日
0 收藏 383 点赞 3,241 浏览 1509 个字

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.

这道题给了两个字符串A和B,说是我们必须调换A中的两个字符的位置一次,问是否能得到字符串B。这道题给的例子又多又全,基本上把所有的 corner cases 都覆盖了,比如我们对比例子2和例子3,可以发现虽然两个例子中A和B字符串都相等,但是仔细观察的话,可以发现 “ab” 中没有相同的字符,而 “aa” 中有相同的字符,那么实际上 “aa” 是可以调换两个字符的位置的,这样还跟字符串B相等,是符合题意的,因为题目要求必须要调换一次位置,若没有相同的字符,是无法调换位置后和B相等的。

那么我们应该可以总结出一些规律了,首先字符串A和B长度必须要相等,不相等的话直接返回 false。假如起始时A和B就完全相等,那么只有当A中有重复字符出现的时候,才能返回 true。快速检测重复字符的方法就是利用 HashSet 的自动去重复功能,将A中所有字符存入 HashSet 中,若有重复字符,那么最终 HashSet 的大小一定会小于原字符串A的长度。对于A和B长度相等,但是字符串本身不相等的一般情况,我们可以记录出所有对应字符不相同的位置,放到一个数组 diff 中,最终判断 diff 数组的长度是否为2,且判断交换位置后是否跟B中对应的位置上的字符相同即可,参见代码如下:

class Solution {
public:
bool buddyStrings(string A, string B) {
if (A.size() != B.size()) return false;
if (A == B && unordered_set<char>(A.begin(), A.end()).size() < A.size()) return true;
vector<int> diff;
for (int i = 0; i < A.size(); ++i) {
if (A[i] != B[i]) diff.push_back(i);
}
return diff.size() == 2 && A[diff[0]] == B[diff[1]] && A[diff[1]] == B[diff[0]];
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/859

参考资料:

https://leetcode.com/problems/buddy-strings/

https://leetcode.com/problems/buddy-strings/discuss/141780/Easy-Understood

[LeetCode All in One 题目讲解汇总(持续更新中…)](https://www.cnblogs.com/grandyang/p/4606334.html)

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,491
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,493
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,294