Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist.
An alphanumeric string is a string consisting of lowercase English letters and digits.
Example 1:
Input: s = "dfa12321afd"
Output: 2
Explanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2.
Example 2:
Input: s = "abc1111"
Output: -1
Explanation: The digits that appear in s are [1]. There is no second largest digit.
Constraints:
1 <= s.length <= 500
s consists of only lowercase English letters and/or digits.
这题需要从一个字符串中找出第二大的整数。我们可以声明两个变量,分别是最大的,第二大的整数。
扫描的时候,假设当前数值比最大的还大,则将最大的数放入第二大的数里,当前放入最大;反之当比最大的小的时候,我们也需要比较和第二大的关系,假设大于第二大,则还是需要赋值的。
class Solution {
public:
int secondHighest(string s) {
int n1 = -1, n2 = -1;
for (auto v : s) {
if (v < '0' || v > '9') {
continue;
}
if (v - '0' > n2) {
n1 = n2;
n2 = v - '0';
} else if (v - '0' < n2 && v - '0' > n1) {
n1 = v - '0';
}
}
return n1;
}
};