给定两个由小写字母构成的字符串 A 和 B ,只要咱们能够经过交换 A 中的两个字母获得与 B
相等的结果,就返回 true ;不然返回 false 。java
示例 1:算法
输入: A = "ab", B = "ba" 输出: true
示例 2:数组
输入: A = "ab", B = "ab" 输出: false
示例 3:post
输入: A = "aa", B = "aa" 输出: true
示例 4:code
输入: A = "aaaaaaabc", B = "aaaaaaacb" 输出: true
示例 5:字符串
输入: A = "", B = "aa" 输出: false
提示:
0 <= A.length <= 20000
0 <= B.length <= 20000
A 和 B 仅由小写字母构成。class
/* 解法一: 思路: 1,当字符串长度不相等,数组长度小于2,的状况下会返回false 2,当字符串长度大于2,且彻底相同时,若是字符串存在重复字符,会返回true 3.当字符串不相同的字符非2时,返回false 4,当字符串不相同字符对为2时,且交叉相同时,返回ture 解法二: 思路:只考虑知足状况的两种状况 1,字符串彻底相同,而且字符串存在重复字符 2,字符串只存在不一样的两个字符,并且俩字符交叉相同 */
import java.util.HashSet; /** @author cosefy @date 2020/7/1 */ public class BuddyStrings { public static void main(String[] args) { String A = "abab"; String B = "abbb"; boolean rs1 = test1(A, B); System.out.println(rs1); boolean rs2 = test2(A, B); System.out.println(rs2); }
//解法一 private static boolean test1(String A, String B) { int lenA = A.length(); int lenB = B.length(); //若是俩字符串长度不一样,或者字符串长度小于2 if (lenA != lenB || lenA < 2 || lenB < 2) return false; //若是俩字符串相同,而且存在重复字符,返回true if (A.equals(B)) { HashSet<Character> set = new HashSet<>(); for (int i = 0; i < lenA; i++) { if (set.contains(A.charAt(i))) return true; else set.add(A.charAt(i)); } return false; } //若是俩字符串不一样,进行判断 int count = 0; //计数不一样的字符个数 int pre = -1, post = -1; //pre,post分别记录俩不一样字符的位置 for (int i = 0; i < lenA; i++) { if (count > 2) { return false; } if (A.charAt(i) == B.charAt(i)) continue; else { ++count; if (pre == -1) pre = i; else post = i; } } return count == 2 && A.charAt(pre) == B.charAt(post) && A.charAt(post) == B.charAt(pre); }
//解法二 public static boolean test2(String A, String B) { if (A.length()!=B.length()) return false; int count = 0;//用来统计俩字符串不相同字符的个数 int sum = 0;//用来检查俩字符串不一样字符串差值之和是否相同 HashSet<Character> set = new HashSet<>(); for (int i = 0; i < A.length(); i++) { set.add(A.charAt(i)); if (A.charAt(i) == B.charAt(i)) continue; else { count++; sum += A.charAt(i) - B.charAt(i); } } return (sum == 0 && count == 2) || (count == 0 && A.length() > set.size()); } }