九度oj 题目1361:翻转单词顺序

题目描述:
JOBDU最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
输入:
每个测试案例为一行,表示一句英文句子。
我们保证一个句子的单词数不会超过600,每个单词的长度也不会超过30。但是需要注意的是Fish是个不拘小节的人,有时候两个单词中间可能会有很多空格。为了方便起见,你可以认为一行的字符总数不会超过50000个,标点符号可以和普通字母一样处理。
输出:
对应每个测试案例,把翻转后的正确的句子单独输出一行。
样例输入:
student. a am I
I'm a Freshman and I like JOBDU!
样例输出:
I am a student.
JOBDU! like I and Freshman a I'm

一开始的代码是这样
 1 #include <cstdio>
 2 #include <cstring>
 3 #include <cstdlib>
 4 
 5 char s[50002];
 6 char word[602][32];
 7 int num[602];
 8 
 9 int main(int argc, char const *argv[])
10 {
11     freopen("input.txt","r",stdin);
12     while(gets(s) != 0) {
13         int cnt = 0;
14         int len = strlen(s);
15         int state = 0;
16         for(int i = 0; i < len; i++) {
17             if(state == 0 && s[i] != ' ') {
18                 num[cnt] = i;
19                 cnt++;
20                 state = 1;
21             }
22             else if(state == 1 && s[i] == ' ') {
23                 state = 0;
24             }
25         }
26         for(int i = 0; i < cnt; i++) {
27             sscanf(&s[num[i]],"%s",word[i]);
28         }
29         printf("%s",word[cnt-1]);
30         for(int i = cnt-2; i >= 0; i--) {
31             printf(" %s",word[i]);
32         }
33         puts("");
34     }
35     return 0;
36 }

提交格式错误。

题目说的不是很清楚,翻转后原来的空格还是需要的,所以采取

转两次的办法

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <cstdlib>
 4 
 5 char s[50002];
 6 
 7 void rev(int from, int to) {
 8     char tmp;
 9     int mid = (from + to)/2;
10     for(int i = from; i <= mid ; i++) {
11         tmp = s[i];
12         s[i] = s[from + to - i];
13         s[from+to-i] = tmp;
14     }
15 }
16 
17 int main(int argc, char const *argv[])
18 {
19     //freopen("input.txt","r",stdin);
20     while(gets(s) != 0) {
21         int len = strlen(s);
22         rev(0, len-1);
23         int from, to;
24         int state = 0;
25         for(int i = 0; i < len; i++) {
26             if(state == 0 && s[i] != ' ') {
27                 state = 1;
28                 from = i;
29             }
30             else if(state == 1 && s[i] == ' ') {
31                 state = 0;
32                 to = i-1;
33                 rev(from,to);
34             }
35         }
36         if(state == 1) {
37             rev(from,len-1);
38         }
39         puts(s);
40     }
41     return 0;
42 }
原文地址:https://www.cnblogs.com/jasonJie/p/5807482.html