[LeetCode] 1790. Check if One String Swap Can Make Strings Equal
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.
Constraints:
1 <= s1.length, s2.length <= 100
s1.length == s2.length
s1
ands2
consist of only lowercase English letters.
仅执行一次字符串交换能否使两个字符串相等。
给你长度相等的两个字符串 s1 和 s2 。一次 字符串交换 操作的步骤如下:选出某个字符串中的两个下标(不必不同),并交换这两个下标所对应的字符。
如果对 其中一个字符串 执行 最多一次字符串交换 就可以使两个字符串相等,返回 true ;否则,返回 false 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/check-if-one-string-swap-can-make-strings-equal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这是一道字符串的题,大体思路是 counting sort 计数排序。题意不难理解,只能 swap 一次,swap 之后两个字符串要相等,也就是说 swap 之前,两个字符串其实是异位词。所以我们把两个字符串扫描一次,同时用一个 map 数组记录字母出现的次数,如果需要 swap 的地方超过两个,那么说明一次 swap 不能满足题意了;扫描结束之后我们再看 map,如果 map 中还有没有归零的字母,那么说明两个字符串其实是不满足互为异位词的,返回 false。
时间O(n)
空间O(1) - map几乎不占空间
Java实现
1 class Solution { 2 public boolean areAlmostEqual(String s1, String s2) { 3 int[] map = new int[26]; 4 int len = s1.length(); 5 // 记录相同位置上字母不同的情况 6 int count = 0; 7 for (int i = 0; i < len; i++) { 8 char c1 = s1.charAt(i); 9 char c2 = s2.charAt(i); 10 if (c1 != c2) { 11 count++; 12 } 13 // 如果不同的字母超过两处,说明一次swap解决不了 14 if (count > 2) { 15 return false; 16 } 17 map[c1 - 'a']++; 18 map[c2 - 'a']--; 19 } 20 21 // 一次swap能解决但是字母其实是不对应的情况 22 for (int i = 0; i < 26; i++) { 23 if (map[i] != 0) { 24 return false; 25 } 26 } 27 return true; 28 } 29 }