Siccome in C++ non riuscivo proprio a farlo.. non riuscivo a scrivere neanche un rigo di codice ho provato a farlo in java. A me nelle mie prove funziona, quando lo carico sul tester per far le prove date dall'università da come risposta TIME LIMIT, e come specifica è: "Il time limit può essere dovuto sia ad una implementazione poco efficiente che ad un loop."
Sapete dirmi secondo voi quale è il problema??? Quali modifiche apportare??
codice:
import java.util.HashMap;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.StringTokenizer;
/**
*
* @author salvo
*/
public class Struttura {
private final HashMap<String, String> chiavi;
private static BufferedReader br;
private final ArrayList<String> lista;
public Struttura() {
this.chiavi = new HashMap<String, String>();
this.lista = new ArrayList<String>();
}
public void leggi() {
br = new BufferedReader(new InputStreamReader(System.in));
int n = -1;
try {
String stringRead = br.readLine();
while (n != -1) {
StringTokenizer st = new StringTokenizer(stringRead, " ");
String primo = st.nextToken();
if (primo.equals("i")) {
n = Integer.parseInt(st.nextToken());
}
}
String id = "continua";
//esce dal ciclo solo quando viene letto <END>
while (!id.equals("<END>")) {
stringRead = br.readLine();
StringTokenizer st = new StringTokenizer(stringRead, " ");
id = st.nextToken().trim();
boolean esci = true;
// Se si stratta di un add entra in questo if
if (id.equals("a")) {
String elem = st.nextToken();
String tag = null;
while (esci) {
if (tag != "-1" && tag != null) {
this.chiavi.put(tag, elem);
}
tag = st.nextToken().trim();
if (tag.equals("-1")) {
esci = false;
}
}
}
// Se si tratta di una stampa entra in questo if
else if (id.equals("s")) {
String subTag = st.nextToken().trim();
lista.clear();
for (Map.Entry<String, String> entry : chiavi.entrySet()) {
String valore = entry.getKey().trim();
if (verificaSottostringa(subTag, valore)) {
this.lista.add(valore);
}
}
if (lista.isEmpty()) {
System.out.println("missing");
} else {
eliminaDupicati(lista);
System.out.println(lista.size());
}
}
}
br.close();
} catch (IOException ex) {
System.out.println("Impossibile leggere i dati");
}
}
// Verifica se è una sottostringa di un'altra parola
public boolean verificaSottostringa(String sottostringa, String daControllare) {
return daControllare.startsWith(sottostringa);
}
// Elimina i risultati da una lista
public void eliminaDupicati(ArrayList lista) {
for (int i = 0; i < lista.size(); i++) {
String currObj = (String) lista.get(i);
for (int k = i + 1; k < lista.size(); k++) {
String tmpObj = (String) lista.get(k);
if (currObj.equals(tmpObj)) {
lista.remove(k);
k--;
}
}
}
}
public static void main(String[] args) {
Struttura struttura = new Struttura();
struttura.leggi();
}
}
Un grazie a tutti quelli che mi aiuteranno.