Word Prefix Triangle
Problem
Read one word and print its prefixes, one on each line. Row 1 has the first letter, row 2 has the first two letters, and the last row is the whole word. Example: india gives i, in, ind, indi, india.
Constraints
- 1 <= length of word <= 100
- The word has no spaces
Examples
Input
india
Output
i in ind indi india
Solutions
A prefix is the beginning of a word. The substring (slice) of the first k letters is the prefix of length k, so one loop from 1 to the word length is enough.
Java 8 has no String.repeat, so we use a small helper method. In Java 11 and newer you can write " ".repeat(count).
/*
* Problem : Prefixes of a word.
* Input : One word without spaces.
* Output : One line for each prefix.
* Approach: Take a part of the word that grows by one letter.
* Time : O(n^2)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String word = new Scanner(System.in).next();
// Step 1: Repeat once for each letter. "length" is the size of the prefix.
for (int length = 1; length <= word.length(); length++) {
// Step 2: Take the first "length" letters. substring(0, 3) of "india" is "ind".
String prefix = word.substring(0, length);
// Step 3: Print the prefix.
System.out.println(prefix);
}
}
}
Hints (2)
- How do you take the first k letters of a string?
- The end index of substring is not included.