Reputation: 848
In Pre-java 7, I could simply do the following:
public static String[] suffixes(String s)
{
int N = s.length();
String[] suffixes = new String[N];
for (int i = 0; i < N; i++)
suffixes[i] = s.substring(i, N);
return suffixes;
}
However, in Java 7, the substring method returns a new string. So the space consumed will be O(n^2)
where n
is the length of the string.
Any quick and easy way to do the same in Java 7 and higher versions?
Upvotes: 1
Views: 759
Reputation: 11
Create your own String (or Suffix) class, as in
http://algs4.cs.princeton.edu/63suffix/SuffixArray.java.html
Upvotes: 0
Reputation: 124734
You can certainly invent an Abstract Data Type to represent a "suffix array":
size()
get(int n)
- return the n-th elementequals(int n, String s)
- compare the n-th element with inputDepending on the functionality you expect from this structure, it might make sense to store the underlying String in a different format, for example as a char[]
, or even both. It doesn't really matter, that will be an implementation detail, encapsulated, hidden from users of your ADT. Start by creating an interface
and define the method it needs to support.
Upvotes: 1