【Google Code Jam】Reverse Words
2016-04-01 21:26
429 查看
Problem here
N test cases follow. For each test case there will a line of letters and space characters indicating a list of space separated words. Spaces will not appear at the start or end of a line.
1 ≤ L ≤ 25
1 ≤ L ≤ 1000
this is a test
foobar
all your base
Case #2: foobar
Case #3: base your all
Problem
Given a list of space separated words, reverse the order of the words. Each line of text contains L letters and W words. A line will only consist of letters and space characters. There will be exactly one space character between each pair of consecutive words.Input
The first line of input gives the number of cases, N.N test cases follow. For each test case there will a line of letters and space characters indicating a list of space separated words. Spaces will not appear at the start or end of a line.
Output
For each test case, output one line containing “Case #x: ” followed by the list of words in reverse order.Limits
Small dataset
N = 51 ≤ L ≤ 25
Large dataset
N = 1001 ≤ L ≤ 1000
Sample
Input
3this is a test
foobar
all your base
Output
Case #1: test a is thisCase #2: foobar
Case #3: base your all
Solution
用struct將字串一塊塊的存在vector,然後放入stack進行反轉輸出#include <iostream> #include <stack> #include <vector> #include <fstream> #include <string> #include <stdio.h> #include <stdlib.h> using namespace std; struct word{ string w; }; ofstream fout("B-large-practice.out"); //ofstream fout("B-small-practice.out"); //ifstream fin("B-small-practice.in"); ifstream fin("B-large-practice.in"); int main(){ int n; fin >> n; fin.ignore(); for(int cnt = 1; cnt <= n; cnt++){ string input; getline(fin, input); vector<word>words; int start = 0; for(int i = 0 ; i <= input.length(); i++){ if(i == input.length()){ string tmp = ""; word wtmp; for(int j = start; j < i; j++){ tmp+= input[j]; } wtmp.w = tmp; words.push_back(wtmp); start = i+1; } if(input[i] == ' '){ string tmp = ""; word wtmp; for(int j = start; j < i; j++){ tmp += input[j]; } wtmp.w = tmp; words.push_back(wtmp); start = i+1; } } stack<word> ws; for(int i = 0; i < words.size(); i++){ ws.push(words[i]); } int count = 0; fout << "Case #" << cnt << ": "; while(!ws.empty()){ if(count != 0){ fout << " " << ws.top().w; }else{ fout << ws.top().w; } ws.pop(); count++; } fout << endl; } return 0; }
相关文章推荐
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- C++实现汉诺塔算法经典实例
- PHP实现克鲁斯卡尔算法实例解析