Leetcode Brush Questions-Intimate Strings

Analysis: If the number of characters in the two strings is not equal, false is returned; the other situations below are based on the same number of characters in the two strings:

If the same number of characters at the same position in two strings is less than or equal to the total number of characters minus 3, then it must return false;

If the same number of characters at the same position in two strings is equal to the total number of characters minus 1, it must return false;

If the same number of characters at the same position in two strings is equal to the total number of characters, then the case is discussed: if there are duplicate characters, return true, otherwise false;

If the same number of characters at the same position in two strings is equal to the total number of characters minus 2, then the case of returning true is to check whether one of the strings can be paired with the other after the remaining two swap positions!

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;

    }
}

The time complexity is O(n):

 

 

 

Guess you like

Origin blog.csdn.net/qq_36428821/article/details/112911623