[leetcode]-859. Buddy Strings(C语言)

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

Note:

  1. 0 <= A.length <= 20000
  2. 0 <= B.length <= 20000
  3. A and B consist only of lowercase letters.
bool buddyStrings(char* A, char* B) {
    int len1=strlen(A),len2=strlen(B);
    if(len1!=len2)
        return false;
    if(len1<2)
        return false;
    int i,j,k,l=0;
    char tem,na[2],n=0;
    for(i=0,j=0;i<len1;i++,j++)
    {
        if(A[i]==B[j])
            continue;
        else
        {
            n++;
            if(n>2)
                return false;
            na[l]=i;
            l++;
        }
            
    }
    if(n==1)
        return false;
    if(n==2)
    {
        if(A[na[1]]==B[na[0]]&&A[na[0]]==B[na[1]])
            return true;
        else
            return false;
    }
    int aa[256]={0};
    for(i=0;i<len1;i++)
    {
        aa[A[i]]++;
        if(aa[A[i]]>=2)
            return true;
    }
    return false;
}

猜你喜欢

转载自blog.csdn.net/shen_zhu/article/details/82056291
今日推荐