Check if anagram

Check if a string is an anagram
/*
 * Anagram.cpp
 *
 *  Created on: Apr 10, 2012
 *      Author: Kiran Hegde
 */

#include <string>
#include <iostream>

using namespace std;

bool isAnagram(string &s1, string &s2) {

    int letters[256];

    for (int i=0; i<256; i++) {
        letters[i] = 0;
    }

    for(unsigned int i=0; i<s1.length(); i++) {
        letters[(int)s1[i]]++;
    }

    for (unsigned int i=0; i<s2.length(); i++) {
        if (--letters[(int)s2[i]] < 0)
            return false;
    }

    return true;
}

/**
 * Test the function
 */
int main() {
    string s1 = string("servant");
    string s2 = string("taverns");
    cout << "s1 = " << s1 << " is " << (isAnagram(s1, s2)? "":"NOT") << " anagram of s2 = "<< s2 << endl;

    s1 = string("tearsdev");
    s2 = string("traverse");
    cout << "s1 = " << s1 << " is " << (isAnagram(s1, s2)? "":"NOT") << " anagram of s2 = "<< s2 << endl;

    return 0;
}
Comments