Leetcode刷题--亲密字符串

分析:如果两个字符串字符个数不相等,则返回false;下面的其他情况都是基于两个字符串字符个数相等:

如果两个字符串相同位置字符相同的个数小于或者等于总字符个数减去3,那么一定返回false;

如果两个字符串相同位置字符相同的个数等于总字符个数减去1,一定返回false;

如果两个字符串相同位置字符相同个数等于总字符个数,那么分情况讨论:如果存在重复字符,返回true,否则false;

如果两个字符串相同位置字符相同个数等于总字符个数减去2,那么返回true的情况就是去校验其中一个字符串剩下两个互换位置后是否可以和另一个对的上!

class Solution {
    public boolean buddyStrings(String A, String B) {
        char [] a = A.toCharArray();
        char [] b = B.toCharArray();
        if(a.length != b.length){
            return false;
        }
        int length = a.length;
        int [] m = new int[length];
        int [] n = new int[length];
        for(int i = 0;i < length;i++){
            m[i] = a[i] -'a' + 1;
        }
        for(int j = 0;j < length;j++){
            n[j] = b[j] - 'a' + 1;
        }
        int count = 0;
        ArrayList<Integer> mList = new ArrayList();
        ArrayList<Integer> nList = new ArrayList();
        for(int k = 0;k < length;k++){
            if(m[k] == n[k]){
                count++;
            }else{
                mList.add(m[k]);
                nList.add(n[k]);
            }
        }
        if(count <= length -3 || count == length - 1){
            return false;
        }
        if(count == length){
            HashSet set = new HashSet();
            for(int p = 0;p < length;p++){
                if(set.contains(m[p])){
                    return true;
                }
                set.add(m[p]);
            }
            return false;
        }
        if(count == length -2){
            if(mList.get(1) == nList.get(0) && mList.get(0) == nList.get(1)){
                return true;
            }else{
                return false;
            }
        }

        return false;

    }
}

时间复杂度为O(n):

猜你喜欢

转载自blog.csdn.net/qq_36428821/article/details/112911623