zoukankan      html  css  js  c++  java
  • 翻转字符串里的单词

    题目:

    给定一个字符串,逐个翻转字符串中的每个单词
    输入: "  hello world!  "
    输出: "world! hello"
    解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。

    来源:力扣(LeetCode)
    https://leetcode-cn.com/problems/reverse-words-in-a-string

    本题存在多种解法,我最初的思路是写一个分割函数,然后将分割的内容装入vector或者stack中,最后连接成一个字符串。

    解法一:

    用sstream最简单

    auto reverseWords(std::string s)
    {
        std::stringstream ss;
        std::string ans="", temp;
        ss << s;
        while (ss >> temp)
        {
    
            ans = " " + temp + ans;
        }
        if (ans != "")
            ans.erase(ans.begin());
        return ans;
    }
    

    解法二:

    #include <iostream>
    #include <vector>
    #include <string>
    #include <sstream>
    #include <iterator>
    #include <algorithm>
    #include <stack>
    
    template<class Container>
    void write_to_cout(Container& container, const char* delimiter = " ")
    {
        std::copy(container.begin(), container.end(),
            std::ostream_iterator<typename Container::value_type>(std::cout, delimiter) );
    }
    
    
    auto my_spilit(std::string& string, const std::string& delimit)
    {
        std::vector<std::string> spilit;
        for (auto i_prev = 0; ;)
        {
            i_prev = string.find_first_not_of(delimit, i_prev);
            if (i_prev == std::string::npos)
            {
                break;
            }
            auto i = string.find_first_of(delimit, i_prev);
            spilit.emplace_back( string.substr(i_prev, i - i_prev) );
            i_prev = i;
        }
        return spilit;
        
     }
    
    auto reverseWords(std::string string)
    {
        std::string ans = "";
        if (string.find_first_of(" ") == std::string::npos)
        {
            return ans;
        }
        std::vector<std::string> new_str = my_spilit(string, " ");
        for(auto i : new_str)
        {
            ans = " " + i + ans;
        }
        ans.erase(ans.begin());
        return ans;
    }
    
    int main()
    {
        std::string string = "  hello  world!  ";
        auto ans = reverseWords(string);
        std::cout << ans << std::endl;
    
    }
    
  • 相关阅读:
    149. Max Points on a Line(js)
    148. Sort List(js)
    147. Insertion Sort List(js)
    146. LRU Cache(js)
    145. Binary Tree Postorder Traversal(js)
    144. Binary Tree Preorder Traversal(js)
    143. Reorder List(js)
    142. Linked List Cycle II(js)
    141. Linked List Cycle(js)
    140. Word Break II(js)
  • 原文地址:https://www.cnblogs.com/codemeta-2020/p/12125040.html
Copyright © 2011-2022 走看看