zoukankan      html  css  js  c++  java
  • [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 };
  • 相关阅读:
    hdu 2490 队列优化dp
    poj 1836 LIS变形
    hdu 3410 单调栈
    51nod 1437
    51nod 1215 单调栈/迭代
    51nod 1102 单调栈
    51nod 1272 思维/线段树
    51nod 1279 单调栈
    SpringMVC收藏
    今天接触枚举类型,感觉是C里面应该才有的东西
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4967286.html
Copyright © 2011-2022 走看看