PTA练习——Hello World for U

Given any string of N (>=5) characters, you are asked to form the characters into the shape of U. For example, "helloworld" can be printed as:

h  d

e  l

l  r

lowo

That is, the characters must be printed in the original order, starting top-down from the left vertical line with n1 characters, then left to right along the bottom line with n2 characters, and finally bottom-up along the vertical line with n3 characters. And more, we would like U to be as squared as possible -- that is, it must be satisfied that n1 = n3 = max { k| k <= n2 for all 3 <= n2 <= N } with n1 + n2 + n3 - 2 = N.

输入
Each input file contains one test case. Each case contains one string with no less than 5 and no more than 80 characters in a line. The string contains no white space.

输出
For each test case, print the input string in the shape of U as specified in the description.

样例输入

helloworld!

样例输出

h   !
e   d
l   l
lowor

思路:

n1和n3是左右两条竖线从上到下的字符个数,n2是底部横线从左到右的字符个数。

题目中给了公式n1 + n2 + n3 – 2 = N,并且我们可以知道n1=n3,n1<=n2,在满足上述条件下n1要最大。

令N=字符串长度+2,进行分类讨论:

  1. 如果N % 3 == 0,n正好被3整除,直接n1 == n2 == n3;
  2. 如果N % 3 == 1,因为n2要比n1大,所以把多出来的那1个给n2
  3. 如果N % 3 == 2, 就把多出来的那2个给n2
    所以得到公式:n1 = N / 3,n2 = N / 3 + N % 3

即步骤为:

1.计算字符串长度l;

2.计算两边的字符数n1= N / 3;

3.计算最后一行中间的字符数(前面每行中间的空格数)space=n2-2;

4.输出每行相应的字符。

#include <iostream>

using namespace std;

int main()
{
    int i,j,n1,l,cnt=0,n2;
    string s;
    while(cin>>s){
        l=s.length();
        n1=(l+2)/3;
        n2=n1+(l+2)%3;
        for(i=1;i<n1;i++){
            cout<<s[cnt];
            for(j=1;j<=n2-2;j++){
                cout<<" ";
            }
            cout<<s[l-cnt-1]<<endl;
            cnt++;

        }
        for(i=cnt;i<cnt+n2;i++){
            cout<<s[i];
        }
    }

    return 0;
}


全部评论

相关推荐

不愿透露姓名的神秘牛友
07-09 12:10
直接上图
牛客13578115...:改得一般,不值80
点赞 评论 收藏
分享
来个大佬救一下,为上投了都是石沉大海了,没实习经历的话怕秋招直接进不了面。什么实习这么难找,基本
心态爆炸了:现在正式的岗位都少,实习基本不咋招的,除了大厂,中小企业其实没那么多岗位需求,就算是有,大多都是招一两个廉价劳动力,同时,他们也会希望你一来就能干活的,没时间培训你,就让你了解公司的项目,你了解完就可以开始干活。再者是,很多低质量的实习其实用处没有那么大的。我去年也是找实习找到破防,最后去了一家深圳的小公司实习,工作对我来说很简单,甚至不如我在学校做的项目,秋招的时候,这段实习经历也并没有帮上什么忙,投递简历,依旧非常低的回复率。低回复率是常态,尤其是找实习,找不到,那就把重心放在优化自己的简历和项目,多看八股文,锻炼自己的面试能力,多看别人的面经,自己模拟面试,等秋招的时候,只要有那么寥寥几次,好好抓住那几次机会。
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务