diff --git a/include/solution/1233.h b/include/solution/1233.h new file mode 100644 index 0000000..0f9a029 --- /dev/null +++ b/include/solution/1233.h @@ -0,0 +1,11 @@ +#ifndef INC_1233_H +#define INC_1233_H +#ifdef __cplusplus +extern "C" +{ +#endif + char **removeSubfolders(char **folder, int folderSize, int *returnSize); +#ifdef __cplusplus +} +#endif +#endif diff --git a/src/1233.c b/src/1233.c new file mode 100644 index 0000000..54668a7 --- /dev/null +++ b/src/1233.c @@ -0,0 +1,30 @@ +#include +#include +#include + +bool startwith(char *p, char *s) +{ + for (; *p && *s; p++, s++) + if (*p != *s) + return false; + + return (!*p && *s) || (!*p && !*s); +} + +char **removeSubfolders(char **folder, int folderSize, int *returnSize) +{ + char **ret = malloc(sizeof(char *)); + *returnSize = 1; + + ret[0] = folder[0]; + for (int i = 1; i < folderSize; i++) + { + if (startwith(ret[*(returnSize)-1], folder[i])) + continue; + + ret = realloc(ret, sizeof(char *) * ++(*returnSize)); + ret[*returnSize - 1] = folder[i]; + } + + return ret; +} \ No newline at end of file diff --git a/tests/test_1233.cpp b/tests/test_1233.cpp new file mode 100644 index 0000000..9a8d1bb --- /dev/null +++ b/tests/test_1233.cpp @@ -0,0 +1,52 @@ +#include +#include +#include +#include +#include + +bool ArrayEquals(char **actual, int actualSize, const std::vector &expected) +{ + if (actualSize != expected.size()) + return false; + + std::vector actualVec(actual, actual + actualSize); + return std::is_permutation(actualVec.begin(), actualVec.end(), expected.begin()); +} + +// 测试类 +class RemoveSubfoldersTest : public ::testing::Test +{ + protected: + void AssertFolders(std::vector input, std::vector expected) + { + int returnSize = 0; + std::vector c_input; + for (auto &s : input) + c_input.push_back(const_cast(s.c_str())); + + char **result = removeSubfolders(c_input.data(), (int)c_input.size(), &returnSize); + ASSERT_TRUE(ArrayEquals(result, returnSize, expected)); + + // 可选释放 result 内存,如果实现中是动态分配的(free) + // 例如:for (int i = 0; i < returnSize; ++i) free(result[i]); + // free(result); + } +}; + +// 示例 1 +TEST_F(RemoveSubfoldersTest, Example1) +{ + AssertFolders({"/a", "/a/b", "/c/d", "/c/d/e", "/c/f"}, {"/a", "/c/d", "/c/f"}); +} + +// 示例 2 +TEST_F(RemoveSubfoldersTest, Example2) +{ + AssertFolders({"/a", "/a/b/c", "/a/b/d"}, {"/a"}); +} + +// 示例 3 +TEST_F(RemoveSubfoldersTest, Example3) +{ + AssertFolders({"/a/b/c", "/a/b/ca", "/a/b/d"}, {"/a/b/c", "/a/b/ca", "/a/b/d"}); +} \ No newline at end of file