5-32 说反话-加强版 (20分)
给定一句英语,要求你编写程序,将句中所有单词的顺序颠倒输出。
输入格式:
测试输入包含一个测试用例,在一行内给出总长度不超过500 000的字符串。字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,单词之间用若干个空格分开。
输出格式:
每个测试用例的输出占一行,输出倒序后的句子,并且保证单词间只有1个空格。
输入样例:
Hello World Here I Come
输出样例:
Come I Here World Hello
思路:
用c++就是while(cin>>str)输入一个单词就往栈中压一个单词,这样不用考虑之间有空格。全部压入后根据判断栈是否为空输出即可。下面的c++代码有详细的解答注释,可以参考。
用java我的想法就是输入一整句话后全部转化成char型从检测到字母开始到检测到一个空格结束即为一个单词,压入栈中。依次循环直至结束后,判断输出栈中元素。
如果会java并且知道我的哪里不对,可以留言一起学习。
java都为最后一个测试点超时。
java超时代码1:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
String[] num = s.split("\\s+");
char[] a = new char[500001];
char[] b = new char[500001];//为了单独判断句首是空格的情况
for (int i = 0; i < s.length(); i++) {
b[i] = s.charAt(i);
}
if (b[0] != ' ') {
for (int i = num.length - 1; i >= 0; i--) {
for (int j = 0; j < num[i].length(); j++) {
a[j] = num[i].charAt(j);
if (a[j] != ' ') {
System.out.print(a[j]);
}
}
if (i != 0) {
System.out.print(" ");
}
}
}else if(b[0] == ' '){
for (int i = num.length - 1; i > 0; i--) {
for (int j = 0; j < num[i].length(); j++) {
a[j] = num[i].charAt(j);
if (a[j] != ' ') {
System.out.print(a[j]);
}
}
if (i != 1) {
System.out.print(" ");
}
}
}
}
}
java超时代码2:
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Stack<String> stack = new Stack<String>();
String s = sc.nextLine();
String[] num = s.split(" ");
String stp = "";
char[] a = new char[500001];
int count = 0;
for(int i=0;i<s.length();i++){
a[i] = s.charAt(i);
}
for(int i=0;i<s.length();i++){
if(a[i] !=' '){
stp += a[i];
}
if(a[i] == ' '&&i != 0||i == s.length()-1){
if(stp != ""){
stack.push(stp);
count ++;
}
stp = "";
}
}
while(!stack.empty()){
for(int i=0;i<count;i++){
if(i!=count-1){
System.out.print(stack.peek()+" ");
}else {
System.out.println(stack.peek());
}
stack.pop();
}
}
}
}
正确c++代码:
”
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main()
{
stack<string> s; //定义一个栈
string sp;
bool flag=false;
while(cin>>sp) //这样直接省略了空格
s.push(sp); //输入一个往栈中压一个
while(!s.empty()) //如果栈不是空
{
if(flag) //代表的是当flag == true时候
cout<<" "; //开始的时候flag==false不会输出空格,最后的时候栈为空了不会进入判断
else
flag=true;
cout<<s.top(); //输出栈顶元素
s.pop(); //移除栈顶元素
}
return 0;
}