PAT-ADVANCED1031——Hello World for U

版权声明:我的GitHub:https://github.com/617076674。真诚求星! https://blog.csdn.net/qq_41231926/article/details/83953866

我的PAT-ADVANCED代码仓:https://github.com/617076674/PAT-ADVANCED

原题链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805462535356416

题目描述:

题目翻译:

1031 U型Hello World

给定任意N(>= 5)个字符的字符串,你需要将字符串组成U形。例如,helloworld可以打印为:

h  d
e  l
l  r
lowo

也就是说,必须以原始顺序打印字符,从左垂线开始自上而下含有n1个字符,然后沿着底线从左到右含有n2个字符,最后沿着右垂直线自下而上含有n3个字符。而且,我们希望U尽可能地成为一个正方形——也就是说,必须满足n​1​​ = n​3 ​​= max { k | k <= n​2​​ 其中,3 <= n​2​​ <= N } 且n​1 ​​+ n​2 ​​+ n​3​​ − 2=N。

输入格式:

每个输入文件包含一个测试用例。 每个测试用例包含一个不少于5个字符且不超过80个字符的字符串。该字符串不包含空格。

输出格式:

对每个测试用例,打印输入字符串的U型输出。

输入样例:

helloworld!

输出样例:

h   !
e   d
l   l
lowor

知识点:字符串

思路:根据输入字符串长度计算出n1、n2和n3的值

n1 = n3 = (len + 2) / 3

n2 = (len + 2) - n1 - n3

其中len为输入字符串的长度。

时间复杂度是O(len)。空间复杂度是O(1)。

C++代码:

#include<iostream>
#include<cstring>

int main(){
	char input[81];
	scanf("%s", input);
	int n1 = (strlen(input) + 2) / 3;
	int n3 = n1, n2 = strlen(input) + 2 - n1 - n3, left = 0, right = strlen(input) - 1;
	for(int i = 0; i < n1 - 1; i++){
		printf("%c", input[left++]);
		for(int j = 0; j < n2 - 2; j++){
			printf(" ");
		}
		printf("%c\n", input[right--]);
	}
	for(int i = left; i <= right; i++){
		printf("%c", input[i]);
	}
	printf("\n");
	return 0;
}  

C++解题报告:

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/83953866