859. Buddy Strings (wrong 4 times so many cases to test and consider) if else**

Posted stiles

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了859. Buddy Strings (wrong 4 times so many cases to test and consider) if else**相关的知识,希望对你有一定的参考价值。

Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B.

 

Example 1:

Input: A = "ab", B = "ba"
Output: true

Example 2:

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

Example 3:

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

Example 4:

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

Example 5:

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

wrong case: aa aa, ab cd, abc dew, 

What a shame!

class Solution {
    public boolean buddyStrings(String A, String B) {
        int a1[] =new int[2];
        int a2[] =new int[2];
        if(A.length()!=B.length() || A.length()==0 || B.length()==0) return false;
        int count = 0;
        for(int i = 0; i<A.length(); i++){
            if(A.charAt(i) != B.charAt(i)) {
                count++;
                if(count > 2) return false;
                a1[count-1] = A.charAt(i);
                a2[count-1] = B.charAt(i);
            }
        }
        if(count == 2 &&a1[0]==a2[1]&&a1[1]==a2[0]) return true;
        //case for aa (A==B and duplicate elements in the String)
        int index[] = new int[26];
        if(A.equals(B)){
            for(int i = 0; i<A.length(); i++){
                index[A.charAt(i)-‘a‘]++;
                if(index[A.charAt(i)-‘a‘]>=2) return true;
            }
            return false;
        }else return false;
        
    }
}

So many if else case to care about! Traps

 

以上是关于859. Buddy Strings (wrong 4 times so many cases to test and consider) if else**的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 859. Buddy Strings

859. Buddy Strings - LeetCode

LeetCode.859-伙伴字符串(Buddy Strings)

leetcode 859. 亲密字符串(Buddy Strings)

859. 亲密字符串

解题报告Leecode 859. 亲密字符串——Leecode每日一题系列