我想的很简单,就是按照一步步输出就可以了。没有用到什么二维数组,只要要个string类型就可以。
题目描述
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.
输入描述:
There are multiple test cases.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.
示例1
输入
复制
helloworld! www.nowcoder.com
输出
复制
h ! e d l l lowor
我的AC代码
#include <bits/stdc++.h>
using namespace std; //“百万”开头
int main()
{
string str;
while(cin >> str)
{
int len = str.length();
int n = 2; //标记竖起来的字符个数,初始是首尾两个字符竖起来
while(len-n >= (n/2+1)) //当下面的字符个数 >= 单边竖起来的字符个数
n += 2; //两边继续各竖起来一个
n -= 2; //最后会多减一次,要减掉
for(int i = 0; i < n/2; i++)
{
int j = len - i - 1; //j标记从末尾开始的字符下标
printf("%c", str[i]);
for(int k = 0; k < len - n - 2; k++) //空格个数为 最后一行的字符个数-2
printf(" ");
printf("%c\n",str[j]);
}
//输出最后一行
for(int k = n/2; k < len - n/2; k++)
printf("%c", str[k]);
printf("\n");
}
return 0;
}