蓝桥杯 算法提高 套正方形 JAVA题解

蓝桥杯 算法提高 套正方形 JAVA题解

问题描述

给定正方形边长width,如图按规律输出层层嵌套的正方形图形。
  注意,为让选手方便观看,下图和样例输出均使用“”代替空格,请选手输出的时候使用空格而不是“”。

width=6:
在这里插入图片描述

输入格式

仅一行一个整数width。

输出格式

按规律输出图形,不要输出多余空格。

样例输入

10

样例输出

在这里插入图片描述

数据规模和约定

width满足width=4n+2,n为正整数。

且width<=50。

思路及代码:

思路就是不断的替代。
首先初始化串为第一行所示的,有n个*的串;
继续观察发现,第二行的可以由第一行用空格替换 * 得到
第三行可以由第二行用 * 替换空格得到
以此类推…
难点在如何定位到该替换的位置
具体请看代码:

import java.util.Scanner;

public class 套正方形 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		judge(n);
	}

	private static void judge(int n) {
		// TODO Auto-generated method stub
		StringBuffer s = new StringBuffer("");
		for(int i=0;i<n;i++) {
			s.append("*");//首先将s初始化为n个*的串
		}
		
		int x=n-2;//x代表的是要替换字符的个数。例如由第二行由第一行替换得到时,替换了4个字符。此后每次替换,需要替换字符的数量依次减2
		int start=0,end=n;//即替换的位置。替换时包括start,不包括end。
		
		String[] str = new String[n];//将每个串保存到str中
		
		int k=0;//用来保存字符串数组
		for(int i=1;i<=n/2;i++,k++) {//只循环一半,另一半由已知的一半得到。
			start++;
			end--;
			str[k] = s.toString();
			
			if(i%2!=0) {//奇数行用空格替换
				String a = "";
				for(int j=0;j<x;j++) {
					a+=" ";
				}
				s.replace(start, end,a);
				x-=2;
			}else { //偶数行用 * 替换
				String a = "";
				for(int j=0;j<x;j++) {
					a+="*";
				}
				s.replace(start, end,a);
				x-=2;
			}
		}/*for*/
		
		for(int i=n/2;i<n;i++) {//另一半由已知的一半得到
			str[i] = str[n-i-1];
		}
		for(int i=0;i<n;i++) {
			System.out.println(str[i]);
		}
	}
}

PS:以下是对 StringBuffer 的 replace说明

replace
public StringBuffer replace(int start,
                            int end,
                            String str)

Replaces the characters in a substring of this sequence with characters in the specified String. The substring begins at the specified start and extends to the character at index end - 1 or to the end of the sequence if no such character exists. First the characters in the substring are removed and then the specified String is inserted at start. (This sequence will be lengthened to accommodate the specified String if necessary.)

参数:

start - The beginning index, inclusive.
end - The ending index, exclusive.
str - String that will replace previous contents.

返回:

This object.

抛出:

StringIndexOutOfBoundsException - if start is negative, greater than length(), or greater than end.

发布了7 篇原创文章 · 获赞 0 · 访问量 444

猜你喜欢

转载自blog.csdn.net/qq_44147512/article/details/104462354
今日推荐