Hollow Pyramid Star Pattern
Problem
Read n and print a hollow pyramid. Only the border of the pyramid has stars: the top star, the two side stars of each row, and the full last row.
Constraints
- 1 <= n <= 50
Examples
Input
3
Output
* * * *****
Solutions
It is the pyramid pattern, but the inside is replaced by spaces. Row r has 2r-3 spaces between the two stars. The first and last rows are special cases.
Java 8 has no String.repeat, so we use a small helper method. In Java 11 and newer you can write "*".repeat(count).
/*
* Problem : Hollow pyramid of stars.
* Input : One integer n (number of rows).
* Output : n lines.
* Approach: Print the first row, the last row, and two stars in the middle rows.
* Time : O(n^2)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method returns the text repeated "count" times. Java 11 has String.repeat for this.
static String repeat(String text, int count) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < count; i++) {
result.append(text);
}
return result.toString();
}
public static void main(String[] args) {
int rows = new Scanner(System.in).nextInt();
// Step 1: Repeat once for each row. Row numbers go from 1 to rows.
for (int row = 1; row <= rows; row++) {
// Step 2: Print the spaces before the first star.
String line = repeat(" ", rows - row);
if (row == 1) {
// Step 3: The first row has only one star.
line = line + "*";
} else if (row == rows) {
// Step 4: The last row is full of stars. It has 2n-1 stars.
line = line + repeat("*", 2 * rows - 1);
} else {
// Step 5: Middle rows have a star, some spaces inside, and a star. Example: row 3 has 3 spaces inside.
line = line + "*" + repeat(" ", 2 * row - 3) + "*";
}
// Step 6: Print the finished line.
System.out.println(line);
}
}
}
Hints (2)
- Solve the normal pyramid first.
- Which rows are special? The first and the last row.