亲密字符串-算法刷题笔记

算法题目

859亲密字符串:

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

示例 1:

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

示例 2:

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

示例 3:

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

示例 4:

输入: A = "aaaaaaabc", B = "aaaaaaacb"
输出: true

示例 5:

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

提示:
0 <= A.length <= 20000
0 <= B.length <= 20000
A 和 B 仅由小写字母构成。

/*
解法一:
    思路:
        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());
​    }
}
posted @ 2020-07-01 22:46  cosefy  阅读(222)  评论(0编辑  收藏  举报