Zhilong Li 4 лет назад
Родитель
Сommit
9d3767a36b
2 измененных файлов с 46 добавлено и 1 удалено
  1. 44 0
      242_valid_anagram.cpp
  2. 2 1
      CMakeLists.txt

+ 44 - 0
242_valid_anagram.cpp

@@ -0,0 +1,44 @@
+// Given two strings s and t, return true if t is an anagram of s, and false otherwise.
+
+// Example 1:
+// Input: s = "anagram", t = "nagaram"
+// Output: true
+
+// Example 2:
+// Input: s = "rat", t = "car"
+// Output: false
+
+#include <vector>
+#include <string>
+#include <iostream>
+
+using namespace std;
+class Solution
+{
+public:
+    bool isAnagram(string s, string t)
+    {
+        vector<int> table(26);
+        if (s.size() != t.size())
+            return false;
+        for (int i = 0; i < s.size(); i++)
+        {
+            table[(int)s[i] - 'a'] += 1;
+            table[(int)t[i] - 'a'] -= 1;
+        }
+        for (auto i : table)
+        {
+            if (i != 0)
+                return false;
+        }
+        return true;
+    }
+};
+
+int main()
+{
+    string s = "car";
+    string t = "rat";
+    Solution so;
+    cout << so.isAnagram(s, t) << endl;
+}

+ 2 - 1
CMakeLists.txt

@@ -4,4 +4,5 @@ project(LC_cpp)
 set(CMAKE_CXX_STANDARD 17)
 set(CMAKE_CXX_STANDARD 17)
 set(CMAKE_RUNTIME_OUTPUT_DIRECTORY executables)
 set(CMAKE_RUNTIME_OUTPUT_DIRECTORY executables)
 add_executable(74_search_a_2d_matrix 74_search_a_2d_matrix.cpp)
 add_executable(74_search_a_2d_matrix 74_search_a_2d_matrix.cpp)
-add_executable(383_ransom_note 383_ransom_note.cpp)
+add_executable(383_ransom_note 383_ransom_note.cpp)
+add_executable(242_valid_anagram 242_valid_anagram.cpp)