LeetCode 557 Reverse Words in a String III(逆转字符串)

来源:互联网 发布:网络教育网 编辑:程序博客网 时间:2024/06/05 22:43

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.

题目大意:给出一个字符串,对其中的每个单词执行逆转操作。

代码如下:

void swap(char* a, char* b){    char temp = *a;    *a = *b;    *b = temp;}void reverse(char* s, int len){    for(int i = 0;i < len/2;i++)        swap(s+i, s+len-i-1);}char* reverseWords(char* s) {    int len = strlen(s);    for(int i = 0, j = 0;i <= len;i++){        if(*(s+i) == ' ' || *(s+i) == '\0'){            reverse(s+j, i-j);            j = i+1;        }    }    return s;}

0 0
原创粉丝点击