汇芳书院

专注计算机视觉、机器学习、分布式计算等领域, 兼聊投资、写作、生活

0%

1796. 字符串中第二大的数字

给你一个混合字符串 s ,请你返回 s 中 第二大 的数字,如果不存在第二大的数字,请你返回 -1 。

混合字符串 由小写英文字母和数字组成。

示例 1:

输入:s = “dfa12321afd”
输出:2
解释:出现在 s 中的数字包括 [1, 2, 3] 。第二大的数字是 2 。
示例 2:

输入:s = “abc1111”
输出:-1
解释:出现在 s 中的数字只包含 [1] 。没有第二大的数字。

提示:

1 <= s.length <= 500
s 只包含小写英文字母和(或)数字。


看似简单,很久不练习,还真不一定能30min内完成。每日练枪!

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
// 范围比较法
int secondHighest1(string s) {
int first = -1,second = -1;
for(auto c : s){
if ('0' <= c && c <= '9'){
int num = c - '0';
if (num > first){
second = first;
first = num;
}else if (num < first && num > second){
second = num;
}
}
}
return second;
}
// 使用有序集合set
int secondHighest(string s) {
std::set<int> candidate;
for(auto c : s){
if ('0' <= c && c <= '9'){
int num = c - '0';
candidate.emplace(num);
}
}
return candidate.size() > 1 ? *prev(prev(candidate.end())) : -1;
}
};
坚持原创分享,您的支持将鼓励我继续创作

欢迎关注我的其它发布渠道

------------- 本文结束,感谢阅读 如有问题可留言交流 -------------