LeetCode 557. Reverse Words in a String III

题目描述

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

题目解读

  • 输入一英文,将这个英文句子中的每个单词进行翻转

解题思路

  • 考虑空格,依次将单词进行翻转
  • 注意:其中有一些数学运算需要仔细把握

Code

# include<stdio.h>
# include<string.h>

char* reverseWords(char* s) 
{
    int i, j;
    int index1 = 0, index2;
    int len;
    char temp;

    len = strlen(s);
    for (i = 0; i < len; i ++)
    {
        if(s[i] == ' ')
        {
            index2 = i - 1;
            for (j = 0; j < ((index2 - index1) + 1) / 2; j ++)
            {
                temp = s[index1 + j];
                s[index1 + j] = s[index1 + ((index2 - index1) + 1) - j - 1];
                s[index1 + ((index2 - index1) + 1) - j - 1] = temp;
            }

            index1 = i + 1;
        }
        else if(i == len - 1)
        {
            index2 = len - 1;
            for (j = 0; j < ((index2 - index1) + 1) / 2; j ++)
            {
                temp = s[index1 + j];
                s[index1 + j] = s[index1 + ((index2 - index1) + 1) - j - 1];
                s[index1 + ((index2 - index1) + 1) - j - 1] = temp;
            }
        }
    }
    
    return s;
}

int main()
{   
    char s[100] = {"Let's take LeetCode contest"};
    char *temp;

    temp = reverseWords(s);
    printf("%s\n", temp);
}

思考

  • 结果差强人意...
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容