题目:
You are given two strings s1
and s2
of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.
Return true
if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false
.
Example 1:
Input: s1 = "bank", s2 = "kanb" Output: true Explanation: For example, swap the first character with the last character of s2 to make "bank".
Example 2:
Input: s1 = "attack", s2 = "defend" Output: false Explanation: It is impossible to make them equal with one string swap.
Example 3:
Input: s1 = "kelb", s2 = "kelb" Output: true Explanation: The two strings are already equal, so no string swap operation is required.
Example 4:
Input: s1 = "abcd", s2 = "dcba" Output: false
Constraints:
1 <= s1.length, s2.length <= 100
s1.length == s2.length
s1
ands2
consist of only lowercase English letters.
思路:
题意大概是给定两个字符串,问是否能够最多只交换其中一个字符串的两个位置使两个字符串相同,这题其实感觉上很熟悉,就是找两个字符串不匹配的点。首先错误可能检查,显然如果两个字符串长度不一样的话不管怎么交换都不可能相同,先排除这种情况。之后同时遍历两个字符串,用一个vector来记录不同的index。如果不同处的数量等于1或者大于等于3,则直接返回false。如果不通的数量等于2并且不同的对应点相等,则返回true。这里不同的对应点指的是比如两个不同的index为0和3,那么s1[0]应该等于s2[3],反之亦然。
代码:
class Solution {
public:
bool areAlmostEqual(string s1, string s2) {
if(s1.size()!=s2.size())
return false;
vector<int> record;
for(int i=0;i<s1.size();i++)
{
if(s1[i]!=s2[i])
record.push_back(i);
if(record.size()>=3)
break;
}
if(record.empty() || (record.size()==2&&s1[record[0]]==s2[record[1]]&&s1[record[1]]==s2[record[0]]))
return true;
return false;
}
};