例子:
char test1[] = "               ";
char test2[] = "   hello  z";
char test3[] = "hello world   ";
char test4[] = "x y z ";
结果:
"               "
"   olleh  z"
"olleh dlrow   "
"x y z "
问题:
反转字符串中的每个世界,忽略空格。
以下是我的代码。基本思想是扫描字符串,当找到一个单词时,然后将其反转。该算法的复杂度为 O(n),其中 n 是字符串的长度。
如何验证它?有更好的解决方案吗?
void reverse_word(char* s, char* e)
{
    while (s < e)
    {
        char tmp = *s;
        *s = *e;
        *e = tmp;
        ++s;
        --e;
    }
}
char* word_start_index(char* p)
{
    while ((*p != '\0') && (*p == ' '))
    {
        ++p;
    }
    if (*p == '\0')
        return NULL;
    else
        return p;
}
char* word_end_index(char* p)
{
    while ((*p != '\0') && (*p != ' '))
    {
        ++p;
    }
    return p-1;
}
void reverse_string(char* s)
{
    char* s_w = NULL;
    char* e_w = NULL;
    char* runner = s;
    while (*runner != '\0')
    {
        char* cur_word_s = word_start_index(runner);
        if (cur_word_s == NULL)
            break;
        char* cur_word_e = word_end_index(cur_word_s);
        reverse_word(cur_word_s, cur_word_e);
        runner = cur_word_e+1;
    }
}