题解 | #Hello World for U#
Hello World for U
https://www.nowcoder.com/practice/c6e414fddd7c401887c350c9cc41f01b
#include <iostream> #include "string" #include "vector" using namespace std; void getHandW(int size, int &height, int &width) { // 根据初始输入的字符串长度,获取U的长和宽 if (size % 3 == 0) { // 情况1:左=下=右 height = size / 3; width = height + 2; } else if ((size + 1) % 3 == 0) { // 情况2:左 = 右 = 下 -1 height = (size + 1) / 3; width = height + 1; // 情况3:左 = 右 = 下 -2 } else { width = height = (size + 2) / 3; } } int main() { string str; while (cin >> str) { // 输入字符串 int width, height; getHandW(str.size(), height, width); // 获取U的长和宽 vector<vector<char>> result(height, vector<char>(width)); // 初始化U矩阵:分配内存 for (int i = 0; i < height; i++) for (int j = 0; j < width; j++) result[i][j]=' '; // 初始化U矩阵:内容置为空格 for (int i = 0; i < height; i++) { // 左 右 result[i][0] = str[i]; result[i][width - 1] = str[str.size() - 1 - i]; } for (int i = 0; i < width - 2; i++) { // 下 result[height - 1][i + 1] = str[height + i]; } for (int i = 0; i < height; i++) { // 结果输出 for (int j = 0; j < width; j++) cout << result[i][j]; cout<<endl; } } return 0; }