Read the input one line at a time and output the current line if and only if
Question:
Read the input one line at a time and output the current line if and only if it is not a suffix of some previous line. For example, if the some line is "0xdeadbeef" and some subsequent line is "beef", then the subsequent line should not be output.
I my current attempt at solving this question is below but it is not efficient enough:
//package comp2402a1;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
public class Part6 {
public static void getWordSuffixes(String text, Set<String> suffixes)
{
for ( int i = 0; i <= text.length(); i++)
{
if (text.substring(text.length() - i, text.length()).length() != 0) {
suffixes.add(text.substring(text.length() - i, text.length()));
}
}
}
/**
* Your code goes here - see Part0 for an example
* @param r the reader to read from
* @param w the writer to write to
* @throws IOException
*/
public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
// Your code goes here - see Part0 for an example
Set<String> suffixes = new HashSet<>();
ArrayList<String> s = new ArrayList<String>();
boolean first = true ;
for (String line = r.readLine(); line != null ; line = r.readLine()) {
if (!suffixes.contains(line) || first) {
s.add(line);
first = false ;
}
getWordSuffixes (line, suffixes);
}
for (String text : s) {
w.println(text);
}
}
/**
* The driver. Open a BufferedReader and a PrintWriter, either from System.in
* and System.out or from filenames specified on the command line, then call doIt.
* @param args
*/
public static void main(String[] args) {
try {
BufferedReader r;
PrintWriter w;
if (args.length == 0) {
r = new BufferedReader( new InputStreamReader(System. in ));
w = new PrintWriter(System. out );
} else if (args.length == 1) {
r = new BufferedReader( new FileReader(args[0]));
w = new PrintWriter(System. out );
} else {
r = new BufferedReader( new FileReader(args[0]));
w = new PrintWriter( new FileWriter(args[1]));
}
long start = System. nanoTime ();
doIt (r, w);
w.flush();
long stop = System. nanoTime ();
System. out .println("Execution time: " + 10e-10 * (stop-start));
} catch (IOException e) {
System. err .println(e);
System. exit (-1);
}
}
}
A Survey of Mathematics with Applications
ISBN: 978-0134112107
10th edition
Authors: Allen R. Angel, Christine D. Abbott, Dennis Runde