存储字符串且忽略字母大小写的数据结构
Data structure that stores strings and ignores letter case
我知道 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"
是否可以实现这样的数据结构?
也许 TreeSet 就是您要找的东西?
TreeSet<String> ts=new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
我不熟悉 Java
,但这里有两个关于如何做到这一点的想法:
- 定义一个新的比较器以在忽略大小写的
HashSet
中使用。
- 让
HashSet
保存一个 string
的列表,它们都具有相同的密钥。也就是说,New York
和 NEW YORK
都将出现在键 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"
我知道 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"
是否可以实现这样的数据结构?
也许 TreeSet 就是您要找的东西?
TreeSet<String> ts=new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
我不熟悉 Java
,但这里有两个关于如何做到这一点的想法:
- 定义一个新的比较器以在忽略大小写的
HashSet
中使用。 - 让
HashSet
保存一个string
的列表,它们都具有相同的密钥。也就是说,New York
和NEW YORK
都将出现在键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"