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 n​1​​ characters, then left to right along the bottom line with n​2​​ characters, and finally bottom-up along the vertical line with n​3​​ characters.

And more, we would like U to be as squared as possible -- that is, it must be satisfied that n​1​​=n​3​​=max { k | k≤n​2​​ for all 3 } with n​1​​+n​2​​+n​3​​−2=N.

题目解释:给一个字符串,然后把它像上述的格式输出,为了追求,尽可能像个正方形满足以下条件 n​1​​=n​3​​=max { k | k≤n​2​​ for all 3<=n2<=N } with n​1​​+n​2​​+n​3​​−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]);
        }

    }
 
}

 

上一篇:1031 Hello World for U (20分)


下一篇:Fritzing软件绘制Arduino面包板接线图传感器模块库文件079