1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
/****************************************************************************************** ******************************************************************************************* Chapter 1 Arrays and Strings * Are two strings anagram? By: Hamed Kiani (July 15, 2015) ****************************************************************************************** ******************************************************************************************/ #include "stdafx.h" #include <iostream> #include <cstring> using namespace std; // additional space: O(n), time: O(n) // how about merge sort with time of O(n log n) and no additional space? bool are_anagram(char *s1, char *s2) { // return false if null // return false for strings with different length if (!s1 || !s2) return false; if (strlen(s1) != strlen(s2)) return false; int count[256] = { 0 }; for (int i = 0; s1[i] != '\0'; i++) { count[(int) s1[i]]++; count[(int) s2[i]]--; } for (int i = 0; i < 256; i++) if (count[i] > 0) return false; return true; } int main() { char s1[] = "mai setin tg twostrings !"; char s2[] = "i am testing two strings!"; bool check = are_anagram(s1, s2); if (check) cout << s1 << " and " << s2 << " are angram " << endl; else cout << s1 << " and " << s2 << " are not angram " << endl; return 0; } |
Comments are closed.
|
A place to practice the coding interview.
AuthorHamed Kiani Categories
All
Archives |