using tail recursion to reverse words of line ( just for fun)
2014-04-25 10:46
501 查看
#include <sstream> #include <string> #include <iostream> class Solution { public: template <typename It> void reverse(It beg, It end) { if (beg < end) { auto v = *beg; reverse(beg, --end, v); } } template <typename It, typename V> void reverse(It beg, It end, V & v) { if (beg < end) { v = *beg; *beg = *end; *end = v; reverse(++beg, --end, v); } } void reverseWords(std::string &s) { reverse(s.begin(), s.end()); std::istringstream iss(s); s = ""; std::string w; if (iss >> s) { reverse(s.begin(), s.end()); reverseWords(iss, w, s); } } void reverseWords(std::istringstream& iss, std::string& w, std::string& s) { if(iss >> w) { reverse(w.begin(), w.end()); s += " "; s += w; reverseWords(iss, w, s); } } }; int main() { std::string line; Solution sln; while (std::getline(std::cin,line)) { sln.reverseWords(line); std::cout << line << std::endl; } }
相关文章推荐
- Unable to find a value for "tStatus" in object of class org.entity.Passport using operator "."
- Are you looking for a way to get the entire text of a word document into a RichEdit without using the Clipboard?
- 83.You are using Enterprise Manager to schedule backups for your database. Which type of script woul
- 93.You are using flat files as the data source for one of your data warehousing applications. To opt
- Linux - How to remove the new line at the end of file when using vim
- Given an array of characters which form a sentence of words, give an efficient algorithm to reverse
- How to Take Ownership of a File/Folder Using Command-Line in Windows 7 or newer version System
- integer addition in terms of bit operators, just for fun
- Unable to find a value for "字段名" in object of class java.lang.String using operator "."
- How to add icon for the item of ListCtrl using C++ (Mail Attachment ListCtrl) - 如何用C++为ListCtrl的Item添加图标(邮件附件ListCtrl)
- What are some of the differences between using recursion to solve a problem versus using iteration?
- Unable to find a value for "dwmc" in object of class "java.lang.String" using operator "." (null
- 论文读书笔记-Using neural network to combine measures of word semantic similarity for image annotation
- Using your laptop to compute PageRank for millions of webpages
- What can I learn right now in just 10 minutes that could be useful for the rest of my life?
- add line order to each line and remove the last match of each line
- 22.You need to create a table for a banking application. One of the columns in the table has the fol
- An A-Z Index of the Bash command line for Linux.摘自https://ss64.com
- How to open the dialog out of iframe by using jquery dialog
- LeetCode解题报告—— Linked List Cycle II & Reverse Words in a String & Fraction to Recurring Decimal