This commit is contained in:
2025-07-20 11:06:49 +08:00
parent f54c320ebf
commit cb718130f7
3 changed files with 72 additions and 0 deletions

11
include/solution/345.h Normal file
View File

@@ -0,0 +1,11 @@
#ifndef INC_345_H
#define INC_345_H
#ifdef __cplusplus
extern "C"
{
#endif
char *reverseVowels(char *s);
#ifdef __cplusplus
}
#endif
#endif

32
src/345.c Normal file
View File

@@ -0,0 +1,32 @@
#include <solution/345.h>
#include <string.h>
#define equal(x) \
((x) == 'a' || (x) == 'A' || (x) == 'e' || (x) == 'E' || (x) == 'i' || (x) == 'I' || (x) == 'o' || (x) == 'O' || \
(x) == 'u' || (x) == 'U')
#define swap(x, y, cb) \
do \
{ \
char t = x; \
x = y; \
y = t; \
cb; \
} while (0)
char *reverseVowels(char *s)
{
for (int i = 0, j = strlen(s) - 1, f = 1; i < j;)
{
if (f && equal(s[i]))
f = 0;
else if (f)
i++;
else if (!f && equal(s[j]))
swap(s[i], s[j], (f = 1, i++, j--));
else
j--;
}
return s;
}

29
tests/test_345.cpp Normal file
View File

@@ -0,0 +1,29 @@
#include <gtest/gtest.h>
#include <solution/345.h>
class ReverseVowelsTest : public ::testing::Test
{
protected:
// 测试包装器
void AssertReverseVowels(const std::string &input, const std::string &expected)
{
char buffer[1024];
strncpy(buffer, input.c_str(), sizeof(buffer));
buffer[sizeof(buffer) - 1] = '\0'; // 保证结尾
char *result = reverseVowels(buffer);
EXPECT_STREQ(result, expected.c_str());
}
};
// 示例 1
TEST_F(ReverseVowelsTest, Example1)
{
AssertReverseVowels("IceCreAm", "AceCreIm");
}
// 示例 2
TEST_F(ReverseVowelsTest, Example2)
{
AssertReverseVowels("leetcode", "leotcede");
}