跳到主要内容

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

链接:1796.字符串中第二大的数字
难度:Easy
标签:哈希表、字符串
简介:给你一个混合字符串 s ,请你返回 s 中 第二大 的数字,如果不存在第二大的数字,请你返回 -1 。

题解 1 - cpp

  • 编辑时间:2022-12-03
  • 内存消耗:6.5MB
  • 编程语言:cpp
  • 解法介绍:遍历。
class Solution {
public:
int secondHighest(string s) {
int n1 = -1, n2 = -1;
for (auto &c : s) {
if (!isdigit(c)) continue;
int num = c - '0';
if (n1 == -1) n1 = num;
else if (num > n1) n2 = n1, n1 = num;
else if (num == n1) continue;
else if (n2 == -1) n2 = num;
else if (num > n2) n2 = num;
}
return n2;
}
};