• 859. Buddy Strings


    Given two strings A and B of lowercase letters, return true if you can swap two letters in A so the result is equal to B, otherwise, return false.

    Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at A[i] and A[j]. For example, swapping at indices 0 and 2 in "abcd" results in "cbad".

    Example 1:

    Input: A = "ab", B = "ba"
    Output: true
    Explanation: You can swap A[0] = 'a' and A[1] = 'b' to get "ba", which is equal to B.
    

    Example 2:

    Input: A = "ab", B = "ab"
    Output: false
    Explanation: The only letters you can swap are A[0] = 'a' and A[1] = 'b', which results in "ba" != B.
    

    Example 3:

    Input: A = "aa", B = "aa"
    Output: true
    Explanation: You can swap A[0] = 'a' and A[1] = 'a' to get "aa", which is equal to B.
    

    Example 4:

    Input: A = "aaaaaaabc", B = "aaaaaaacb"
    Output: true
    

    Example 5:

    Input: A = "", B = "aa"
    Output: false
    

    Constraints:

    • 0 <= A.length <= 20000
    • 0 <= B.length <= 20000
    • A and B consist of lowercase letters.
    class Solution {
        public boolean buddyStrings(String A, String B) {
            int n1 = A.length(), n2 = B.length();
            if(n1 != n2 || n1 == 0 || n2 == 0) return false;
            if(A.equals(B)) {
                int[] count = new int[26];
                for(char c : A.toCharArray()) count[c - 'a']++;
                
                for(int i : count) {
                    if(i > 1) return true;
                }
                return false;
            }
            else {
                int fir = -1, sec = -1;
                for(int i = 0; i < n1; i++) {
                    if(A.charAt(i) != B.charAt(i)) {
                        if(fir == -1) fir = i;
                        else if(sec == -1) sec = i;
                        else return false;
                    }
                }
                return sec != -1 && A.charAt(fir) == B.charAt(sec) && A.charAt(sec) == B.charAt(fir);
            }        
        }
    }

    这也能是easy?泥头车创撕你。

    corner case很多,首先当两个相等,判断下里面有没有一个char出现了两次或以上,如果有就返回true,否则返回false,因为不可能符合题意。

    如果不相等,也要看是不是只出现了两个位置不相等,而且交换后相等,所以只能判断到第二个不相等的,如果不相等的小于2或者大于2,都返回错误。只有两个不相等的时候,且交换他俩后相等,才能返回true。

  • 相关阅读:
    ES6数组的扩展--Array.from()和Array.of()
    前端面试中的各种方法实现
    理解 JavaScript call()/apply()/bind()
    【前端面试】变量和类型计算
    Kubernetes1.3新特性:支持GPU
    撸了一个微信小程序项目
    微信开发(调用各种接口)
    Android 神兵利器之通过解析网页获取到的API数据合集,可拿来就用
    Kubernetes1.4正式发布
    Kubernetes1.4即将发布
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13807581.html
Copyright © 2020-2023  润新知