字符排版问题(网易实习笔试题Mark)

(下述题目中的数据范围与原题不一定符合)

字符串中标点符号:“,”(逗号)  "."(句号)  "!"(感叹号)   "?"(问号)  均占一个字符。

排版要求:

1.每行第一个字符不能为标点符号;

2.遇到“\n”时强制换行;

3.每行字符串长度不能大于每行最大字符数。

输入第一行为测试点个数,第二行为字符宽度(小于25)和每行最大字符数(小于1000),第三行为需要处理的字符串。

输出每个测试点的最小行数。如果字符排版不能满足上述要求则输出“impossible”。

例如:

输入:

3

2  5

hello,world!

1  1

hello,world!

3  10

nonewline\nnew!\nline

 

输出:

6

impossible

7

 

代码c++(没有进行数据检验):

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

int main()
{
	int num;
	cin >> num;

	for (int i = 0; i < num; i++)
	{
		int count = 0;
		int size, maxS;
		cin >> size >> maxS;
		string str;
		cin >> str;
		int n = maxS / size;
		int j=0;
		if ((str.find(",")>=0 || str.find(".") >=0 || str.find("!") >= 0 || str.find("?") >= 0) && n == 1)
		{
			cout << "impossible" << endl;
			continue;
		}

		while(j<str.size())
		{
			if (str.size() - j >= n)
			{
				if (str.substr(j+n , 1) == ","||str.substr(j+n, 1) == "!" ||
					str.substr(j+n, 1) == "." || str.substr(j+n, 1) == "?")
				{
					if (n > 1)
					{
						cout << str.substr(j, n - 1) << endl;
						j = j + n - 1;
						count++;
						continue;
					}
					
				}
				string str1 = str.substr(j, str.size());
				int pos = str1.find("\\n");
				if (pos>=0&&pos<n)
				{
					if (pos ==0)
					{
						j = j+2;
						continue;
					}
					else
					{
						cout << str.substr(j, pos) << endl;
						j = j+pos + 2;
						count++;
						continue;
					}
					
				}
				cout << str.substr(j, n) << endl;
				j = j + n;
				count++;
			}
			else
			{
				cout << str.substr(j, str.size() - j) << endl;
				j = j + n;
				count++;
			}
		}
		cout << count<<endl;
	}
	system("pause");
    
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值