2015-07-13 9 views
5

So che la struttura dati HashSet<String> può memorizzare stringhe univoche e dire se la stringa è presente con complessità O (1), perché usa il codice hash. Si può raggiungere la stessa complessità, se voglio ignorare il caso di lettere? Il prossimo caso d'uso dovrebbe funzionare:Struttura dati che memorizza le stringhe e ignora la maiuscola

Set<String> set = new IgnoreLetterCaseSet(); 
set.add("New York"); 
set.contains("new york") == true; 
set.contains("NEW YORK") == true; 

set.each(it -> print it) ---> prints "New York" 

È possibile implementare tale struttura dati?

+0

@ Dave chiave ultima riga di codice - stampa di New York, come è stato inserito, non riesco a normalizzare la stringa minuscolo all'inserimento –

+0

Cosa succede se hai creato una nuova classe che ha esteso 'String', sovrascrivendo i metodi' .equals() 'e' .hashCode() '? –

+1

@jameslarge La classe stringa è definitiva, non può essere estesa. – dave

risposta

3

basta usare un HashMap con stringa originale come valore e minuscole uno per

Map<String, String> map = new HashMap<>(); 
map.add("New York".toLowerCase() ,"New York"); 
map.containsKey("new york".toLowerCase()) == true; 
map.containsKey("NEW YORK".toLowerCase()) == true; 

map.values().each(it -> print it) ---> prints "New York" 
+0

quindi devo avvolgere una HashMap per ottenere O (1) immagino –

6

Forse TreeSet è quello che stai cercando?

TreeSet<String> ts=new TreeSet<String>(String.CASE_INSENSITIVE_ORDER); 
+1

'SortedSet ts = new TreeSet <> (String.CASE_INSENSITIVE_ORDER);' dove 'CASE_INSENSITIVE_ORDER' è un comparatore. –

+0

bello, ma può essere fatto in O (1)? –

0

io sono familiarità con Java, ma qui ci sono due idee su come si potrebbe fare questo:

  1. definire un nuovo operatore di confronto da utilizzare nella HashSet che ignora caso.
  2. Il numero HashSet contiene un elenco di string s che hanno tutte la stessa chiave. Cioè, New York e NEW YORK saranno entrambi nella lista sotto la chiave new york.
Problemi correlati