PAT 1031.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.

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

我的解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <string>

//解题思路:
//1.计算n1,n2:通过循环枚举找k的最大取值即n1,同时保存n2的值
//2.将字符填入二维数组,U型之外的部分以空格填充

using namespace std;

//以U型打印s
void printU(const string &s)
{
int n1 = 0, n2, size = s.size();
char tmp[100][100];

//计算n1,n2
int t = size;
while (t >= 3) {
int k = t;
while (k) {
if (2 * k + t - 2 == size) {
if (n1 < k) {
n1 = k;
n2 = t;
}
break;
}
--k;
}
--t;
}

//以空格填充
for (int i = 0; i < n1; ++i) {
for (int j = 0; j < n2; ++j) {
tmp[i][j] = ' ';
}
}

//字符填入矩阵
int x = 0, y = 0, z = 0;
for (int i = 0; i < n1 - 1; ++i) {
tmp[x++][y] = s[z++];
}
for (int i = 0; i < n2; ++i) {
tmp[x][y++] = s[z++];
}
--y;
for (int i = 0; i < n1; ++i) {
tmp[--x][y] = s[z++];
}

//打印
for (int i = 0; i < n1; ++i) {
for (int j = 0; j < n2; ++j) {
cout << tmp[i][j];
}
cout << endl;
}
}

int main()
{
string s;

cin >> s;
printU(s);

return 0;
}
Author: sphc
Link: https://jkuvw.xyz/archives/60d364b5/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
微信打赏
支付宝打赏