Last active
August 29, 2015 14:02
-
-
Save xun-gong/6f344017108913a9ec8c to your computer and use it in GitHub Desktop.
CareerCup1.3.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Chapter 1 | |
* 1.3 Given two strings, write a method to decide if one is a permutation of the other. | |
*/ | |
#include <iostream> | |
#include <string> | |
using namespace std; | |
bool permutation(char* str1, char* str2) | |
{ | |
if (strlen(str1) != strlen(str2)) {r | |
eturn false; | |
} | |
else if (strlen(str1) == 0 && strlen(str2) == 0) { | |
cout << "They're both empty string." << endl; | |
} | |
else { | |
int counter[256]; // for extended ASCII | |
memset(counter, 0, sizeof(counter)); // set counter to 0 | |
// Counter acts as indicator(elegant&efficient) | |
// No need to initialize two different counter to record | |
// then compare each slot's value | |
for (int i = 0; i < strlen(str1); i++) { | |
++counter[(int)str1[i]]; | |
--counter[(int)str2[i]]; | |
} | |
for (int i; i < 256; i++) { | |
if (counter[i] != 0) { | |
return false; | |
} | |
} | |
} | |
return true; | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
char str1[] = "mary"; | |
char str2[] = "army"; | |
cout << permutation(str1, str2) << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment