题解 | #Hello World for U#
Hello World for U
https://www.nowcoder.com/practice/c6e414fddd7c401887c350c9cc41f01b
#include<iostream> #include<cstring> using namespace std; int main() { char str[100] = {'\0'}; //初始化 while (cin>>str) //配合键盘的ctrl+Z,然后回车,从而停止输入 { int len = strlen(str); //字符串长度 if (len < 5) { cout << "字符串长度应大于等于5,请重新输入字符串!"<<endl; continue; } //用暴力枚举法确定n1,n2,n3 int n1 = 0; int n2; int n3 = 0; for (n2 = 3; n2 <= len; n2++) { if ((len + 2 - n2) % 2 == 0) //因为n1 + n2 + n3 - 2 = len,且n1,n2,n3都得是整数 { n1 = (len + 2 - n2) / 2; } else { continue; } if (n1 > n2) { continue; //不符合“n1必须小于等于n2”这个条件 } else if (n1 <= n2) { break; //此时的n1一定是符合题意的n1的最大值 } n3 = n1; } //在二维字符数组中填充U型字符 char arr[100][100]; //初始化 for (int i = 0; i < 100; i++) for (int j = 0; j < 100; j++) arr[i][j] = ' '; int idx = 0; //显示当前处于字符串str[]的什么位置 for (int i = 0; i < n1; i++) //填充n1列 arr[i][0] = str[idx++]; for (int j = 1; j < n2; j++) arr[n1 - 1][j] = str[idx++]; //填充n2行 for (int i = n1 - 2; i >= 0; i--) arr[i][n2 - 1] = str[idx++]; //填充n3列 //打印输出 for (int i = 0; i < n1; i++) { for (int j = 0; j < n2; j++) { cout << arr[i][j]; } cout << endl; } } return 0; }