CareerCup-1.4

Write a method to decide if two strings are anagrams or not.

Solution1#

先排序再比较字符串是否相同

Solution2#

统计字符数比较数量是否相等

#include <iostream>
using namespace std;

bool anagram(char* s, char* t) {
    if(strlen(s) != strlen(t)) return false;
    int count[256] = {0};
    for(char* p = s; *p!='\0'; p++)
    {
        count[*p]++;
    }
    for(char* p = t; *p!='\0'; p++)
    {
        count[*p]--;
    }
    for(int i=0; i<256; i++)
    {
        if(count[i] != 0)
            return false;
    }
    return true;
}

int main()
{
    cout<<anagram("abdde", "aedd1b");
    system("pause"); 
};

Comments

comments powered by Disqus