翻轉字符串里的單詞


題目:

給定一個字符串,逐個翻轉字符串中的每個單詞
輸入: "  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;

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM