Given an input string, reverse the string word by word.
For example,
Given s = “the sky is blue”,
return “blue is sky the”.Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
JavaScript 解法如下:
/**
* @author chenliang
*/
var reverseWords = function(str) {
strArray = isString(str).split(" ");
strArray.reverse();
/* for(i = 0 ; i< strArray.length; i++){
if(strArray[i] == "" && strArray[i+1] == ""){
strArray.splice(i+1,1);
}
}*/
return isString(strArray.join(" "));
};
var isString = function(str){
var reg = new RegExp(" +","g");
while(str[0] == " "){
str = str.substr(1);
}
return str.replace(reg," ");
}
其中注释掉的代码块,是因为LeetCode不支持splice()删除元素。帮采用正则方法。整体思路简单,就是检查字串是否符合要求;再分隔成数组;数组反转后再拼接。