我知道HashSet<String>数据结构可以存储唯一的字符串,并说字符串是否存在O(1)复杂性,因为它使用哈希码。如果我想忽略字母大小写,是否可以实现相同的复杂性?下一个用例应该工作:

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"

是否可以实现这种数据结构?

最佳答案

只需使用HashMap,将原始字符串作为值,并将小写字母作为键

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"

07-24 09:37
查看更多