题解 | Hello World for U

Hello World for U

https://www.nowcoder.com/practice/c6e414fddd7c401887c350c9cc41f01b

#include <stdio.h>
#include <cstring>
using namespace std;
int main() {
    char str[85]; //定义一个字符数据存储字符串
    while (scanf("%s", str) != EOF) { //有多组测试用例
        int i = 0;
        int k = 0;
        int j = 0;
        int len = strlen(str);//计算字符串的实际长度
        int n = len - 1; //字符串数组的最大下标
        int r;
        int s;
        //枚举暴力遍历找到符合n1 + n2 + n3 - 2 = len且n1==n3且 n1<=n2的唯一组合并记录下来
        for ( i = 2; i <= 80 ; i++) {
            for ( j = 3 ; j <= 80 ; j++) {
                if (2 * i + j - 2 == len &&
                        i <= j) { //由于公式的唯一性对每个输入字符串只有唯一解
                    //如helloworld! len = 11 ,i = 4 j = 5
                    r = i; //记录公式的唯一解n1和n2
                    s = j;
                }
            }
        }
        //找到对应的n1=n3=r=4,n2=s=5;
        while (k != r -
                1) { //当k(统计值)不等于n1-1时即k!=3对称的进行输出(一头一尾)
            printf("%c", str[k]);
            k++;//输出第二个...
            for ( i = 0 ; i < s - 2; i++) { //输出空格
                printf(" ");
            }
            printf("%c", str[n]); //从尾部进行输出
            n--;//输出倒数第二个...
            printf("\n");//每输出一组数据后进行换行
        }
        //循环终止时(多执行了一次++or--)k= k +1 = 3; n=n-1=7
        //从3-7依次进行输出即可刚好对应上一个while循环结束时的初始条件和终止条件(带等号)
        for (j = k ; j <= n; j++) {
            printf("%c", str[j]);
        }
        printf("\n"); //最后需进行换行
    }
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务