|
| 1 | +// Check Permutation: Given two strings, write a method to decide if one is a |
| 2 | +// permutation of the other. |
| 3 | +// |
| 4 | +// Hints: #1, #84, #722, #737 |
| 5 | + |
| 6 | +#include <algorithm> |
| 7 | +#include <iostream> |
| 8 | +#include <string> |
| 9 | + |
| 10 | +using namespace std; |
| 11 | + |
| 12 | +// ------------------------------------------------------------------------------------------------ |
| 13 | + |
| 14 | +string sort(const string &s) { |
| 15 | + string sort_s(s); |
| 16 | + sort(sort_s.begin(), sort_s.end()); |
| 17 | + return sort_s; |
| 18 | +} |
| 19 | + |
| 20 | +bool permutation_1(const string &s, const string &t) { |
| 21 | + if (s.length() != t.length()) { |
| 22 | + return false; |
| 23 | + } |
| 24 | + return sort(s) == sort(t); |
| 25 | +} |
| 26 | + |
| 27 | +// ------------------------------------------------------------------------------------------------ |
| 28 | + |
| 29 | +bool permutation_2(const string &s, const string &t) { |
| 30 | + if (s.length() != t.length()) { |
| 31 | + return false; |
| 32 | + } |
| 33 | + |
| 34 | + int letters[128] = {0}; |
| 35 | + for (const char &c : s) { |
| 36 | + letters[c]++; |
| 37 | + } |
| 38 | + |
| 39 | + for (int i = 0; i < t.length(); ++i) { |
| 40 | + char c = t[i]; |
| 41 | + letters[c]--; |
| 42 | + if (letters[c] < 0) { |
| 43 | + return false; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + return true; |
| 48 | +} |
| 49 | + |
| 50 | +// ------------------------------------------------------------------------------------------------ |
| 51 | + |
| 52 | +#include "gtest/gtest.h" |
| 53 | + |
| 54 | +TEST(PermutationTest, Trivial) { |
| 55 | + |
| 56 | + EXPECT_TRUE(permutation_1("abcd", "dcba")); |
| 57 | + EXPECT_FALSE(permutation_1("abcd", "daba")); |
| 58 | + |
| 59 | + EXPECT_TRUE(permutation_2("abcd", "dcba")); |
| 60 | + EXPECT_FALSE(permutation_2("abcd", "daba")); |
| 61 | +} |
0 commit comments