杭电OJ 1062. Text Reverse

题目描述:

Problem Description

Ignatius likes to write words in reverse way. Given a single line of text which is written by Ignatius, you should reverse all the words and then output them.

 

Input

The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow.
Each test case contains a single line with several words. There will be at most 1000 characters in a line.

 

Output

For each test case, you should output the text which is processed.

 

Sample Input

3

olleh !

dlrow m'I morf .

udh I ekil .mca

 

Sample Output

hello world!

I'm from hdu.

I like acm.

 

思路:

这道题目要求把句子中乱序的单词翻转过来,输出正常的句子。

我的想法是:

(1)设置两个工作指针,分别是头指针,指向乱序单词的首字母;尾指针,指向乱序单词的尾字母;

(2)从尾指针位置倒序输出字符,到头指针位置截止,获得一个正确的单词,并将这个单词拼接到正常的句子中;

(3)移动头指针和尾指针到下一个单词,重复第(3)步,直到最后,获得完整的正常句子;

 

实现(C++):

#include <iostream>
#include <string>
using namespace std;

int main(){
	
	int n;
	cin>>n;
	getchar();
	
	while(n--){
		
		string str;
		getline(cin, str); //输入一个字符串str,cin不将空格作为输入的结束符 
		
		int str_length=str.length();
		str[str.length()]=' '; //在str字符串后加上一个空格字符,方便与后面的计算 
		str_length++; //字符串长度相应加1 
	
		int count=0; //用于统计str字符串中有几个单词 
		for(int i=0; i<str_length; i++)
			if(str[i]==' ')
				count++;

		char result[10001]; //result作为最终结果输出 
		int head_ptr=0; //头指针,指向str中每个单词的起始字符 
		int tail_ptr=0; //尾指针,指向str中每个单词的终止字符 
		
		int l=0;  
		for(int j=0; j<count; j++){ //依次将每个单词翻转,并拼接到result中 
			while(str[tail_ptr+1]!=' ')
				tail_ptr++;	
						
			for(int k=tail_ptr; k>=head_ptr; k--) 
				result[l++]=str[k];
				
			result[l++]=' '; //在翻新单词后插入一个空格 
	
			head_ptr=tail_ptr=l; //头指针、尾指针分别指向下一个单词的起始字符 
		}
		
		result[str_length]='\0'; //result最后会多出一个空格,应该删除 
		cout<<result<<endl;	
	}	

	return 1;
} 

 

提交答案,OJ结果竟然是Runtime Error!

而我线下测试程序时是可以正常编译并运行的,成功通过了题目给出的用例,如图:

 

可能是OJ的某个中间用例没有通过。

问题还没解决,请大佬们多指教。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值