当前位置:网站首页>Interview question 01.02 Determine whether it is character rearrangement - auxiliary array algorithm

Interview question 01.02 Determine whether it is character rearrangement - auxiliary array algorithm

2022-07-07 22:03:00 Mr Gao

Interview questions 01.02. Determine whether to rearrange characters for each other

Given two strings s1 and s2, Please write a program , After determining the character rearrangement of one of the strings , Can it be another string .

Example 1:

Input : s1 = “abc”, s2 = “bca”
Output : true

Example 2:

Input : s1 = “abc”, s2 = “bad”
Output : false

For this question , In fact, it's relatively simple , We can add an auxiliary array to judge the problem , Make an auxiliary array , Storage s1 The number of letters in the , then , Yes s2 Subtract the number of letters stored in , The number of each letter stored in the auxiliary array is 0, return true, Otherwise return to false
The solution code is as follows :

bool CheckPermutation(char* s1, char* s2){
    
    int r[26];
    int i=0;
    for(i=0;i<26;i++){
    
        r[i]=0;
    }
    i=0;
    while(s1[i]!='\0'){
    
        r[s1[i]-'a']++;
        i++;
    }
    i=0;
    while(s2[i]!='\0'){
    
        r[s2[i]-'a']--;
        i++;
    }
     for(i=0;i<26;i++){
    
        if(r[i]!=0){
    
            return false;
        }

    }
    return true;

}
原网站

版权声明
本文为[Mr Gao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071415029358.html