[LeetCode][JavaScript]Reverse Words in a String

Reverse Words in a String

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.

click to show clarification.

Clarification:

 

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.

https://leetcode.com/problems/reverse-words-in-a-string/

 

 

 


 

 

反转字符串中的单词。

万能的正则表达式。

 

1 /**
2  * @param {string} str
3  * @returns {string}
4  */
5 var reverseWords = function(str) {
6     return str.trim().split(/\s+/).reverse().join(' ');
7 };

 

正常解法, javascript 不能in-place改变字符串,开了个变量。

 

 1 /**
 2  * @param {string} str
 3  * @returns {string}
 4  */
 5 var reverseWords = function(str) {
 6     var start = -1, end, i, result = "";
 7     for(i = 0; i < str.length; i++){
 8         if(!/\s/.test(str[i])){
 9             if(start === -1){
10                 start = i;
11             }    
12             if(start !== -1 && (!str[i + 1] || /\s/.test(str[i + 1]))){
13                 end = i;
14                 result = str.substring(start ,end + 1) + ' ' + result;
15                 start = -1;
16                 i++;
17             }
18         }
19     }
20     return result.trim();
21 };

 

 

posted @ 2015-11-15 20:34  `Liok  阅读(435)  评论(0编辑  收藏  举报