Skip to content

Instantly share code, notes, and snippets.

@vo
Created March 3, 2014 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vo/9331376 to your computer and use it in GitHub Desktop.
Save vo/9331376 to your computer and use it in GitHub Desktop.
Checking if one string is a permutation of another
#include <iostream>
void build_histogram(std::string s, int * m) {
size_t len = s.length();
for(int i = 0; i < len; ++i)
m[s[i]] +=1;
}
bool check_permutation(std::string s1, std::string s2)
{
int s1map[255], s2map[255];
for(int i=0; i<255; s1map[i]=0, s2map[i]=0, ++i);
build_histogram(s1, s1map);
build_histogram(s2, s2map);
for(int i=0; i<255; ++i)
if(s1map[i] != s2map[i]) return false;
return true;
}
int main()
{
std::string s1, s2;
std::cout << "Enter string 1: ";
std::getline(std::cin, s1);
std::cout << "Enter string 2: ";
std::getline(std::cin, s2);
std::cout << "String 1: " << s1 << std::endl;
std::cout << "String 2: " << s2 << std::endl;
bool is_permutation = check_permutation(s1, s2);
std::cout << "String 1 "
<< ( is_permutation ? "IS" : "IS NOT")
<< " a permutation of String 2." << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment