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;
        }
    };
  • 相关阅读:
    CSS的浮动和清除
    外边距合并现象
    CSS 盒子模型
    CSS样式三
    CSS的继承与优先级
    CSS 样式二
    UVA 11922 Permutation Transformer(平衡二叉树)
    HDU 3726 Graph and Queries(平衡二叉树)(2010 Asia Tianjin Regional Contest)
    POJ 1873 The Fortified Forest(枚举+凸包)
    POJ 2069 Super Star(计算几何の最小球包含+模拟退火)
  • 原文地址:https://www.cnblogs.com/grandyang/p/6065544.html
Copyright © 2011-2022 走看看