1. The simplest method is to sort these strings (O(nlogn)) and then compare them(O(n)).
bool isAnagram1(string s, string t){ // why cannot use &?
if(s=="" || t=="") return false;
if(s.length() != t.length()) return false;
sort(&s[0], &s[0]+s.length());// why must use &(reference)?
sort(&t[0], &t[0]+t.length());
if(s == t) return true;
else return false;
}
2. Use scoreboard to note the times each ASCII shows, when find one in s1, add it, then if find it in s2 too, minus it, to see if the scoreboard is == 0;
#include
#include
#include
using namespace std;
bool isAnagram1(string s, string t){ // why cannot use &?
if(s=="" || t=="") return false;
if(s.length() != t.length()) return false;
sort(&s[0], &s[0]+s.length());// why must use &(reference)?
sort(&t[0], &t[0]+t.length());
if(s == t) return true;
else return false;
}
bool isAnagram(string s, string t){
if(s=="" || t=="") return false;
if(s.length() != t.length()) return false;
int len = s.length();
int c[256];
memset(c, 0, sizeof(c));
for(int i=0; i
Compiling the source code....
$g++ -std=c++11 main.cpp -o demo -lm -pthread -lgmpxx -lgmp -lreadline 2>&1
Executing the program....
$demo
c[99]=1
c[100]=-1
1