242_valid_anagram.cpp 855 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // Given two strings s and t, return true if t is an anagram of s, and false otherwise.
  2. // Example 1:
  3. // Input: s = "anagram", t = "nagaram"
  4. // Output: true
  5. // Example 2:
  6. // Input: s = "rat", t = "car"
  7. // Output: false
  8. #include <vector>
  9. #include <string>
  10. #include <iostream>
  11. using namespace std;
  12. class Solution
  13. {
  14. public:
  15. bool isAnagram(string s, string t)
  16. {
  17. vector<int> table(26);
  18. if (s.size() != t.size())
  19. return false;
  20. for (int i = 0; i < s.size(); i++)
  21. {
  22. table[(int)s[i] - 'a'] += 1;
  23. table[(int)t[i] - 'a'] -= 1;
  24. }
  25. for (auto i : table)
  26. {
  27. if (i != 0)
  28. return false;
  29. }
  30. return true;
  31. }
  32. };
  33. int main()
  34. {
  35. string s = "car";
  36. string t = "rat";
  37. Solution so;
  38. cout << so.isAnagram(s, t) << endl;
  39. }