Skip to content

Instantly share code, notes, and snippets.

@honghaoz
Last active August 29, 2015 14:02
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 honghaoz/7ed6a6f4155b2ce02f56 to your computer and use it in GitHub Desktop.
Save honghaoz/7ed6a6f4155b2ce02f56 to your computer and use it in GitHub Desktop.
Check whether one string is a permutation of the other
include<set>
include<cstring>
using namespace std;
bool checkSame(string a, string b) {
if (a.length() != b.length()) {
return false;
}
map<char, int> testMap;
int length = (int)a.length();
int count = -1;
for (int i = 0; i < length; i++) {
count = testMap[a[i]];
testMap[a[i]] = count + 1;
}
length = (int)b.length();
count = -1;
for (int i = 0; i < length; i++) {
count = testMap[b[i]];
if (count == 0) {
return false;
} else {
if (count == 1) {
testMap.erase(b[i]);
} else {
testMap[b[i]]--;
}
}
}
if (testMap.size() == 0) {
return true;
} else {
return false;
}
}
bool checkSame1(string a, string b) {
multiset<char> testSet1;
multiset<char> testSet2;
for (string::iterator it = a.begin(); it != a.end(); it++) {
testSet1.insert(*it);
}
for (string::iterator it = b.begin(); it != b.end(); it++) {
testSet2.insert(*it);
}
if (testSet1 == testSet2) {
return true;
} else {
return false;
}
}
int main() {
string a = "12345";
string b = "54123";
printf("%d\n", checkSame(a, b));
printf("%d\n", checkSame1(a, b));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment