A Journey 2 Eternity

Check a string is a permutation of the other string

Posted on: July 13, 2012

We are going to write a method to decide if one is a permutation of the other (i.e GOD is a permutation of DOG)

bool IsPermutation(const string &s, const string &t)
{
	if (s.length() != t.length()) {
		return false;
	}

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

	// count the number of each char in s
	for (unsigned int i = 0; i < s.length(); i++) {
		letters[s.at(i)]++;
	}

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

	return true;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Pages

Categories

July 2012
M T W T F S S
« Jun   Aug »
 1
2345678
9101112131415
16171819202122
23242526272829
3031  

Blog Stats

  • 27,261 hits
%d bloggers like this: