@adamkubriczky/TeemingLargeSnowleopard
C++

No description

repl talk
Files
  • main.cpp
main.cpp
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
#include <string>
#include <iostream>

using namespace std;

/*
 * Hoping for only uppercase letters and spaces as input for s1 and s2.
*/
int anagram(string s1, string s2) {
  int abc[26] = {0};
  int ana = 1; //suppose they are anagrams
  //For every uppercase letters in s1, increase the corresponding counter in the abc
  for (int i = 0; i < s1.length(); i++) {
    if (s1[i] >= 'A' && s1[i] <= 'Z') {
      abc[s1[i] - 'A'] += 1;
    }
  }
  //For every uppercase letters in s2, decrease the corresponding counter in the abc
  for (int i = 0; i < s2.length(); i++) {
    if (s2[i] >= 'A' && s2[i] <= 'Z') {
      abc[s2[i] - 'A'] -= 1;
    }
  }
  //If there is a non-zero value in the abc (difference in letters), then s1 and s2 are no anagrams.
  for (int i = 0; i < 26; i++) {
    if (abc[i] != 0) {
      ana = 0;
      break;
    }
  }
  return ana;
} //As the first for loop does n * constant work, the second loop does m * constant work and the third
  //loop does constant work, the whole algorithm is in O(n + m)
  //The algorithm is correct, because the whole abc array is zero at the end if and only if the two
  //strings contain the same characters and the same amount of each.

int main(int argc, char *argv[]) {
  cout << anagram("LOLLIPOP", "POLIPLOL") << endl; //true
  cout << anagram("LOLLI POP", "POL IP LOL") << endl; //true
  cout << anagram("TOM", "TON") << endl; //false
  cout << anagram("TO M", "TON") << endl; //false
  return 0;
} 
gcc version 4.6.3