diff --git a/include/solution/387.h b/include/solution/387.h new file mode 100644 index 0000000..d34d863 --- /dev/null +++ b/include/solution/387.h @@ -0,0 +1,11 @@ +#ifndef INC_387_H +#define INC_387_H +#ifdef __cplusplus +extern "C" +{ +#endif + int firstUniqChar(char *s); +#ifdef __cplusplus +} +#endif +#endif diff --git a/src/387.c b/src/387.c new file mode 100644 index 0000000..da51b7c --- /dev/null +++ b/src/387.c @@ -0,0 +1,17 @@ +#include +#include + +int firstUniqChar(char *s) +{ + int hash[26]; + memset(hash, 0, sizeof(int) * 26); + + for (int idx = 0; s[idx]; idx++) + hash[s[idx] - 'a']++; + + for (int idx = 0; s[idx]; idx++) + if (hash[s[idx] - 'a'] == 1) + return idx; + + return -1; +} \ No newline at end of file diff --git a/tests/test_387.cpp b/tests/test_387.cpp new file mode 100644 index 0000000..480ac81 --- /dev/null +++ b/tests/test_387.cpp @@ -0,0 +1,51 @@ +#include +#include + +class FirstUniqCharTest : public ::testing::Test +{ + protected: + void AssertFirstUniqChar(const std::string &input, int expected) + { + char buf[1001]; + strncpy(buf, input.c_str(), sizeof(buf)); + buf[1000] = '\0'; // 防止越界 + int result = firstUniqChar(buf); + EXPECT_EQ(result, expected); + } +}; + +// 示例 1:leetcode → 'l' 是第一个唯一字符,索引 0 +TEST_F(FirstUniqCharTest, Example1) +{ + AssertFirstUniqChar("leetcode", 0); +} + +// 示例 2:loveleetcode → 'v' 是第一个唯一字符,索引 2 +TEST_F(FirstUniqCharTest, Example2) +{ + AssertFirstUniqChar("loveleetcode", 2); +} + +// 示例 3:aabb → 没有唯一字符,返回 -1 +TEST_F(FirstUniqCharTest, Example3) +{ + AssertFirstUniqChar("aabb", -1); +} + +// 边界测试:空字符串 +TEST_F(FirstUniqCharTest, EmptyString) +{ + AssertFirstUniqChar("", -1); +} + +// 边界测试:单字符 +TEST_F(FirstUniqCharTest, SingleChar) +{ + AssertFirstUniqChar("z", 0); +} + +// 更多测试:末尾唯一字符 +TEST_F(FirstUniqCharTest, UniqueAtEnd) +{ + AssertFirstUniqChar("aabbc", 4); // 'c' 是唯一字符 +} \ No newline at end of file