存储字符串并忽略字母大小写的数据结构

5 java string set data-structures

我知道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"
Run Code Online (Sandbox Code Playgroud)

是否有可能实现这样的数据结构?

小智 6

也许TreeSet正在寻找什么?

TreeSet<String> ts=new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
Run Code Online (Sandbox Code Playgroud)


use*_*037 3

只需使用一个 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"
Run Code Online (Sandbox Code Playgroud)