PAT A1031 Hello World for U (20 分)

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 n​2 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 形的笔画顺序输出各个字符.

思路:

(1)计算出n1(==n3)和n2的值,n1=(N+2)/3,n2=(N+2)-2*n1,N为字符串的长度;
(2)分割键入的字符串str,设计三个字符串str1[n1+1],str2[n2+1],str3[n1+1]分别存放 U 形字符串的左、下、右部分;
(3)分割字符数组时需要先将其转化为string型字符串再调用substr()函数,分割后的string型字符串再转化成字符数组输出.

代码:

#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
const int maxlen=81;
int main(){
	char str[maxlen];
	scanf("%s",str);
	int N=strlen(str),n1=(N+2)/3,n2=(N+2)-2*n1;
	string a(str),strn1=a.substr(0,n1),strn2=a.substr(n1-1,n2),strn3=a.substr(n1+n2-2,n1);//将字符数组str转化成string型字符串,再对其分割 
	char str1[n1+1],str2[n2+1],str3[n1+1];
	strcpy(str1,strn1.c_str()),strcpy(str2,strn2.c_str()),strcpy(str3,strn3.c_str());//将分割后的string型字符串转化成字符数组以便于输出 
	for(int i=0;i<n1-1;i++){
		printf("%c",str1[i]);
		for(int j=0;j<n2-2;j++){
			printf(" ");
		}
		printf("%c\n",str3[n1-1-i]);
	}
	printf("%s\n",str2);
	return 0;
} 

词汇:

form 形成
vertical 垂直的
square 正方形
specified 指定的
white space 空格

发布了26 篇原创文章 · 获赞 0 · 访问量 485

猜你喜欢

转载自blog.csdn.net/PanYiAn9/article/details/102537421