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
题目大意:用所给字符串按U型输出。n1和n3是左右两条竖线从上到下的字符个数,n2是底部横线从左到右的字符个数。
#include <iostream>
#include <string>
using namespace std;
/*
n1 与 n3 的长度 小等于 n2 的长度
n2 大于等于 3 小于等于 N n1 + n2 + n3 - 2 = N
因此 n1 + n2 + n3 = N + 2
所以我们去看 字符串长度是多少 再加上2
令len = N + 2
不难发现 n1 与 n3的 长度就是 len / 3
n2特殊处理 当 len % 3 == 0 时 n2 = len / 3
当 len % 3 == 1 时 n2 = len / 3 + 1
当 len % 3 == 2 时 n2 = len / 3 + 2
*/
int main(){
string s;
cin >> s;
int len = s.size() + 2;
int n1 = len / 3, n3 = len / 3;
int n2 = n1 + (len % 3);
//双指针 i初始指向开头 j初始指向结尾 当i达到len - n3 - 1 输出完毕 跳出循环
//结合上边所给的输出格式,很容易明白,就不做赘述了
for(int i = 0, j = len - 2 - 1; i < len - n3 - 1; i++, j--){
if(i < n1 - 1){ // i == n1 - 1 时就需要输出 最后一行了
printf("%c",s[i]);
printf("%*s",n2 - 2,""); //可以记住这个输出多个空格的写法 当然也可以用循环解决
printf("%c\n",s[j]);
}
else{
printf("%c",s[i]); //输出最后一行
}
}
printf("\n");
return 0;
}