当前位置:网站首页>普歌 -- getOrDefault()方法理解
普歌 -- getOrDefault()方法理解
2022-06-28 06:29:00 【Dear-JC】
解析getOrDefault()方法
介绍
getOrDefault(Object key, V defaultValue)
在操作Map集合时,判断是否存储着这个key。如果有返回对应的value值,若不存在,则返回自定义的默认值defaultValue值。
代码实现
LeetCode第387题:字符串中第一个唯一字符
public static void main(String[] args) {
String s = "loveleetcode";
System.out.println(firstUniqChar(s));
}
public static int firstUniqChar(String s) {
Map<Character, Integer> frequency = new HashMap<Character, Integer>();
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
// 当集合中这个key时,就使用这个value值,没有默认defaultValue
frequency.put(ch, frequency.getOrDefault(ch, 0) + 1); // 将前面的值放进去,按默认值+1计算,只有当出现重复的时候再按ch的value计算。
}
for (int i = 0; i < s.length(); ++i) {
if (frequency.get(s.charAt(i)) == 1) {
// 返回指定的字符,将字符当作key进行返回
return i;
}
}
return -1; // 返回最末的值
}
完结
边栏推荐
- 整型提昇和大小端字節序
- OpenSCAP 简介
- Exception handling (I) -- null pointer and array index out of bounds
- Paper recommendation: efficientnetv2 - get smaller models and faster training speed through NAS, scaling and fused mbconv
- FPGA - 7 Series FPGA selectio -07- iserdese2 of advanced logic resources
- Object object to list collection
- Alibaba cloud SMS service (Complete Guide), SMS sending function implementation.
- [staff] arpeggio mark
- Difficulty calculation of Ethereum classic
- 5-minute NLP: summary of time chronology from bag of words to transformer
猜你喜欢

借助nz-pagination中的let-total解析ng-template

Yygh-7-user management

Drop down list processing in Web Automation

浮动与定位

socke.io長連接實現推送、版本控制、實時活躍用戶量統計

Speech enhancement - spectrum mapping

Xcode13.3.1 error reported after pod install

FPGA - 7系列 FPGA SelectIO -07- 高级逻辑资源之ISERDESE2

Socket. Io long Connection Push, version Control, Real - Time Active user volume Statistics

Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance
随机推荐
MySQL(二)——基本操作
Rn7302 three-phase electric quantity detection (based on STM32 single chip microcomputer)
Interpretation of Blog
Slow content advertising: the long-term principle of brand growth
使用SQL select count distinct查询语句统计数据库中某个字段的唯一值总数量
Sharing tips for efficient scripting
JDBC学习(一)——实现简单的CRUD操作
eyebeam高级设置
Idea generates entity classes from database tables
@The reason why the Autowired annotation is empty
Scripting and programming languages
Example of MVVM framework based on kotlin+jetpack
mac下安装多个版本php并且进行管理
ThreadLocal
Linked list (I) - remove linked list elements
Yygh-7-user management
Caused by: com. fasterxml. jackson. databind. exc.InvalidDefinitionException: Cannot construct instance
Unity packaging webgl uses IIS to solve the error
fpm工具安装
Yolact++ Pytorch环境