判断两个字符串是不是互为anagrams

来源:互联网 发布:java游戏移植官网 编辑:程序博客网 时间:2024/06/02 03:02

Description
Write a function that checks whether two words are anagrams. Two words are anagrams if they contain the same letters in any order. For example, “silent” and “listen” are anagrams. The header of the function is as follows:

bool isAnagram(const char * const s1, const char * const s2)

代码实现:

#include<iostream>#include<string.h>using namespace std;bool isAnagram(const char * const s1, const char * const s2) {    if(s1 == NULL || s2 == NULL){        return false;    }    int len1 = strlen(s1);    int len2 = strlen(s2);    if(len1 != len2)        return false;    int flag = true;    //使用哈希表来判断,因为只有字符串中最多只有128个不同的字符    //所以可以建立一个array[128]的哈希表     int array[128] = {0};    for(int i = 0; i < len1; i++){        array[*(s1+i)]++;    }    for(int i = 0; i < len1; i++){        array[*(s2+i)]--;    }    for(int i = 0; i < 128; i++){        if(array[i] != 0){            flag = false;            break;        }    }    return flag;}
0 0
原创粉丝点击