leet242.有效的字母異位詞

給定兩個字符串 s 和 t ,編寫一個函數來判斷 t 是否是 s 的字母異位詞。

示例 1:

輸入: s = "anagram", t = "nagaram"
輸出: true
示例 2:

輸入: s = "rat", t = "car"
輸出: false
說明:
你可以假設字符串只包含小寫字母。

進階:
如果輸入字符串包含 unicode 字符怎麼辦?你能否調整你的解法來應對這種情況?

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/valid-anagram
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

/**
problem:有效的字母異位詞
說明:
你可以假設字符串只包含小寫字母。

進階:
如果輸入字符串包含 unicode 字符怎麼辦?你能否調整你的解法來應對這種情況?
*/

#include<stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

/**
思路一:遍歷字符數組,將每個字符號 - ‘a’ ,作爲新數組下表,最後對比新數組

**/
bool isAnagram(char * s, char * t)
{

    int len1 = strlen(s);
    int len2 = strlen(t);
    ///strlen()函數求出的字符串長度爲有效長度,既不包含字符串末尾結束符 ‘\0’;
    ///sizeof()操作符求出的長度包含字符串末尾的結束符 ‘\0’;
    if(len1 != len2)
        return false;

    int num1[26] = {0};
    int num2[26] = {0};
    int loc1,loc2;


    for(int i = 0; i<len1; ++i)
    {
        loc1 =(int) (s[i] - 'a');
        loc2 = (int)(t[i] - 'a');
        num1[loc1]++;
        num2[loc2]++;
    }
    for(int i = 0; i <26; ++i)
    {

        if(num1[i] != num2[i])
        {
            return false;
        }
    }
    return true;

}


int main(void)
{
    char ar1[8] = {'a','n','a','g','r','a','m'};
    char ar2[8] = {'n','a','g','a','r','a','m'};
    char ar3[] = "cx";
    char ar4[] = "nl";

    printf("%d",'z'-'a'); ///共計26個

    bool result = isAnagram(ar3,ar4);
    if(result)
        printf("true\n");
    else
        printf("false\n");
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章