1031 Hello World for U (20 point(s)) - C语言 PAT 甲级

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/huaxuewan/article/details/101015540

1031 Hello World for U (20 point(s))

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   !
e   d
l    l
lowor

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.

Input Specification:

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.

Output Specification:

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

Sample Input:

helloworld!

Sample Output:

h   !
e   d
l    l
lowor

题目大意:

输入的字符串,按照 U 字型输出;

n1 和 n3 表示两条竖线上字符的总个数,n2 表示底部横线上字符的总个数,并要求:

  1. n1 == n3
  2. n2 >= n1
  3. n1 取尽可能大的值
设计思路:

难点在于确定 n1、n2 的值;

因为 U 分为 n1、n2、n3 三条边,且重叠了两个字符,所以设:

  • n = 原字符串长度 + 2 = n1 * 2 + n2
    • 若 n % 3 == 0,则 n1 == n2 == n3
    • 若 n % 3 > 0,并且需要 n2 >= n1,那么把多出的余数给 n2 就行了;
  • 所以 n1 = n / 3,n2 = n / 3 + n % 3;

确定了三条边的长度,利用一个头指针和一个尾指针,按行输出原字符串即可

编译器:C (gcc)
#include <stdio.h>
#include <string.h>

int main(void)
{
        char str[81], *p, *q;
        int n1, n2, count;
        int i, j;

        scanf("%s", str);

        count = strlen(str) + 2;
        p = str;
        q = str + (count - 2 - 1);
        n1 = count / 3;
        n2 = count / 3 + count % 3;
        for (i = 0; i < n1 - 1; i++) {
                printf("%c", *p);
                p++;
                for (j = 1; j < n2 - 1; j++)
                        printf(" ");
                printf("%c\n", *q);
                q--;
        }
        for (p; p <= q; p++)
                printf("%c", *p);

        return 0;
}

猜你喜欢

转载自blog.csdn.net/huaxuewan/article/details/101015540
今日推荐