Luminous Script Segmentation Count
You are given a script string and a dictionary of allowed phrases. The job is to count how many different ways the full script can be segmented so that every piece is one of those phrases.
This is not about rearranging phrases. The order is fixed by the original script, and every character must be covered exactly once from left to right.
For example, if the script is empty, the answer is 1 because there is exactly one way to segment it: choose nothing. If the script can be broken in multiple valid phrase sequences, all of those count toward the total.
So the task is to count all valid left-to-right segmentations of the script using only the allowed phrases.
Example Input & Output
The script can be restored as "lantern fair" or "lan tern fair".
Only the segmentation "river lights" matches the script.
The empty script has one valid segmentation that uses no phrases.
Algorithm Flow

Solution Approach
This is a counting version of word break, so dynamic programming works well. Let dp[i] mean the number of ways to segment the suffix that starts at position i.
The base case is:
That says once we reach the end of the string, we have found one complete valid segmentation.
At each position i, we try every phrase that matches the script starting there. If a phrase of length len fits, then every valid segmentation of the remaining suffix contributes to the current answer:
We fill the DP from right to left, or use memoized recursion to compute the same idea on demand.
At the end, dp[0] is the total number of valid segmentations for the whole script.
Best Answers
import java.util.*;
class Solution {
public int count_segmentations(String s, String[] dictionary) {
Set<String> words = new HashSet<>(Arrays.asList(dictionary));
int n = s.length();
int[] dp = new int[n + 1];
dp[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = 0; j < i; j++) {
if (words.contains(s.substring(j, i))) {
dp[i] += dp[j];
}
}
}
return dp[n];
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
