pat甲级 1031 Hello World for U

题目:

Given any string of N (≥) 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 n2​​ 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 | kn2​​ for all 3 } with n1​​+n2​​+n3​​2=N.

题目解释:给一个字符串,然后把它像上述的格式输出,为了追求,尽可能像个正方形满足以下条件 n1​​=n3​​=max { k | kn2​​ for all 3<=n2<=N } with n1​​+n2​​+n3​​2=N.

import java.util.Scanner;
public class Main {

    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        char str[] = scanner.next().toCharArray();
        int N  = str.length;
        int max = 0;
        int n2;
        for(int i=3;i<=N;i++){//求出满足条件的n2
            n2 = i;
            if(((N+2)-n2)%2==1){//除去n1和n2非整数的情况
                continue;
            }
            int  k= ((N+2)-n2)/2;
            if(k>n2){//排除n1比n2大的情况
                continue;
            }
            if(max<k){
                max = k;
            }

        }
        for(int i=0;i<max-1;i++){//输出
            System.out.print(str[i]);
            for(int j = 0;j<N-2*(max);j++){
                System.out.print(" ");
            }
            System.out.println(str[N-1-i]);
        }
        for(int i=max-1;i<=N-max;i++){
            System.out.print(str[i]);
        }

    }
 
}

 

posted @ 2021-04-07 17:12  chenyuan#  阅读(32)  评论(0编辑  收藏  举报