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.

思考:

  1.如何找到空格位置?

  2.如何截断字符串并把它旋转?

思路:可以用start和end变量找到并控制空格位置,然后再用循环把字符串逆序。

解法一: 用JavaScript内置方法

/**
 * @param {string} s
 * @return {string}
 */
var reverseWords = function(s) {
    var str = s.split(" ");  //截断成数组
    for(let i=0;i<str.length;i++){
        str[i] = str[i].split("").reverse().join(""); //把各子字符串截断为数组,再逆转,再拼成字符串
    }
    return str.join(" ");  //再用空格分开字符串
};

解法二:C语言

char* reverseWords(char* s) {
    int i=0,j=0;
    int start=0,end=0;
    int len=strlen(s);
    char temp;
    for(i=0;i<=len;i++){
        if(s[i]==' '||s[i]=='\0'){  //找到空格位置
             end=i-1;
            int result = end+start;
             for(j=start;j<=result/2;j++){   //旋转字符串
                 temp=s[j];
                 s[j]=s[result-j];
                 s[result-j]=temp;
             }  
             start=i+1;
        }
    }
    return s;
}

 

posted @ 2017-10-29 17:09  im.lhc  阅读(252)  评论(0编辑  收藏  举报