Efficiency
Your solve()
is O(n2), where n is the length of the input string.
As it turns out, there is an O(n) algorithm to produce exactly the lengths of the common prefixes you want, called the Z Algorithm. In the standard terminology used to describe the algorithm, each of those common prefixes is called a "Z-box". A full explanation of the algorithm is beyond the scope of this review, but you should be able to find some online resources that illustrate it well. The basic idea is that information about previously analyzed Z-boxes can be used for shortcuts.
Here is a Python implementationPython implementation, which translates very easily into Java.
Driver
I suggest writing main()
this way:
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int numCases = scanner.nextInt();
while (numCases-- > 0) {
System.out.println(sum(z(scanner.next())));
}
}
}
Note the following improvements:
- Open the
Scanner
using a try-with-resources block. - Use static methods.
new Solution()
is pointless, since the object keeps no state. - Rename the
no_cases
variable according tojavaConventions
. - Eliminate the
i
variable. - Separate concerns, such that finding the prefix lengths, summing, and printing are done in separate functions.