• 翻转字符串里的单词


    题目:

    给定一个字符串,逐个翻转字符串中的每个单词
    输入: "  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;
    
    }
    
  • 相关阅读:
    java和.NET的比较
    联想笔记本不能无线上网
    js根据给定的日期计算当月有多少天
    jQuery中live()变更
    C#操作xml文件
    SQL server的with的用法(一)
    jquery拖拽实现UI设计组件
    自定义弹出框
    第一个超级简单Node.js实例
    windows 下使用redis
  • 原文地址:https://www.cnblogs.com/codemeta-2020/p/12125040.html
Copyright © 2020-2023  润新知