String leetcode 859 intimate string

Subject content:

Given two strings A and B composed of lowercase letters, as long as we can get the same result as B by exchanging two letters in A, return true; otherwise, return false.

The definition of swapping letters is to take two subscripts i and j (subscripts start from 0). As long as i!=j, swap the characters at A[i] and A[j]. For example, swapping the elements of subscript 0 and subscript 2 in "abcd" can generate "cbad".

Example 1:

Input: A = "ab", B = "ba"
Output: true
Explanation: You can exchange A[0] ='a' and A[1] ='b' to generate "ba", at this time A and B are equal.

Example 2:

Input: A = "ab", B = "ab"
Output: false
Explanation: You can only exchange A[0] ='a' and A[1] ='b' to generate "ba". At this time, A and B are not equal.

Example 3:

Input: A = "aa", B = "aa"
Output: true
Explanation: You can exchange A[0] ='a' and A[1] ='a' to generate "aa", at this time A and B are equal.

Example 4:

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

Example 5:

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

prompt:

0 <= A.length <= 20000
0 <= B.length <= 20000
A 和 B 仅由小写字母构成。

Source: LeetCode
Link: https://leetcode-cn.com/problems/buddy-strings

answer:

bool buddyStrings(char * A, char * B){
    
    
//分情况,先比较两个字符串的长度,不相等直接false,
//两个字符串相等的时候,判断字符串中有没有重复的元素,有则返回true,无则返回false
//两个字符串不相等,判断字符串是否是有两个字母不相同
    int count=0;
    int count1=0;
    int a[2]={
    
    0};
    int b[2]={
    
    0};
    int alen=strlen(A);
    int blen=strlen(B);
    char hashmap[26]={
    
    0};
    //字符串长度相等的时候
    if(alen==blen){
    
    
        //字符串相同的时候
        if(strcmp(A,B)==0){
    
    
            for(int i=0;i<alen;i++){
    
    
                for(int j =0;j<count;j++){
    
    
                    //判断是否有两个字母相等,有直接返true;
                    if(hashmap[j]==A[i]){
    
    
                        return true;
                    }
                }
                hashmap[count]=A[i];
                count++;
            }
        }
        //字符串长度相同,但字符串不相同
        else{
    
    
            for(int i=0;i<alen;i++){
    
    
                if(A[i]!=B[i]){
    
    
                    if(count1<2){
    
    
                        a[count1]=A[i];
                        b[count1]=B[i];
                    }
                    count1++;
                }
            }
            //判断字符串是否只有两个字符不相等,且位置交换后相等
            if(count1==2&&a[0]==b[1]&&a[1]==b[0]){
    
    
                return true;
            }

        }

    }

    return false;
}

to sum up:

According to the situation, first compare the length of the two strings, if they are not equal, directly false, when the
two strings are equal, judge whether there are duplicate elements in the string, return true if there is, and return false if the
two strings are not equal , To determine whether the string has two different letters

Guess you like

Origin blog.csdn.net/mogbox/article/details/112919051
Recommended