zoukankan      html  css  js  c++  java
  • [LintCode] 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".

    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.

    LeetCode上的原题,请参见我之前的博客Reverse Words in a String

    解法一:

    class Solution {
    public:
        /**
         * @param s : A string
         * @return : A string
         */
        string reverseWords(string s) {
            int storeIndex = 0, n = s.size();
            reverse(s.begin(), s.end());
            for (int i = 0; i < n; ++i) {
                if (s[i] != ' ') {
                    if (storeIndex != 0) s[storeIndex++] = ' ';
                    int j = i;
                    while (j < n && s[j] != ' ') s[storeIndex++] = s[j++];
                    reverse(s.begin() + storeIndex - (j - i), s.begin() + storeIndex);
                    i = j;
                }
            }
            return string(s.begin(), s.begin() + storeIndex);
        }
    };

    解法二:

    class Solution {
    public:
        /**
         * @param s : A string
         * @return : A string
         */
        string reverseWords(string s) {
            string res = "", t = "";
            istringstream is(s);
            while (getline(is, t, ' ')) {
                if (t.empty()) continue;
                res = (res.empty() ? t : (t + " " + res));
            }
            return res;
        }
    };

    解法三:

    class Solution {
    public:
        /**
         * @param s : A string
         * @return : A string
         */
        string reverseWords(string s) {
            istringstream is(s);
            is >> s;
            string t; 
            while (is >> t) {
                s = t + " " + s;
            }
            return (s[0] == ' ') ? "" : s;
        }
    };
  • 相关阅读:
    CSP游戏 4
    CSP 交通规划
    CSP 地铁修建
    CSP 通信网络
    CSP URL映射
    CSP 权限查询
    CSP Markdown
    CSP JSON 查询
    SQL里的子查询
    SQL里的操作符
  • 原文地址:https://www.cnblogs.com/grandyang/p/6065544.html
Copyright © 2011-2022 走看看