来源:力扣(LeetCode)
描述:
给你一个混合字符串 s ,请你返回 s 中 第二大 的数字,如果不存在第二大的数字,请你返回 -1 。
混合字符串 由小写英文字母和数字组成。
示例 1:
输入:s = "dfa12321afd"
输出:2
解释:出现在 s 中的数字包括 [1, 2, 3] 。第二大的数字是 2 。
 
示例 2:
输入:s = "abc1111"
输出:-1
解释:出现在 s 中的数字只包含 [1] 。没有第二大的数字。
 
提示:
- 1 <= s.length <= 500
 - s 只包含小写英文字母和(或)数字。
 
方法:直接遍历
思路与算法
题目要求找到字符串 s 中第二大的数字,我们用 first 、second 分别记录 s 中第一大的数字与第二大的数字,且初始化时二者均为 −1 ,当我们遍历字符串中第 i 个字符 s[i] 时:
- 如果第 s[i] 为字母则跳过;
 - 如果第 s[i] 为数字,则令 num 表示 s[i] 对应的十进制数字: 
  
- 如果满足 num > first,则当前最大的数字为 num,第二大的数字为 first,则此时更新 second 等于当前的 first,更新当前的 first 为 num 即可。
 - 如果满足 second < num < first,则当前最大的数字为 first ,第二大的数字为 num ,则此时更新当前的 second 为 num 即可。
 - 如果满足 num ≤ second ,则此时不需要任何更新。
 
 
最终返回第二大数字 second 即可。
代码:
class Solution {
public:
    int secondHighest(string s) {
        int first = -1, second = -1;
        for (auto c : s) {
            if (isdigit(c)) {
                int num = c - '0';
                if (num > first) {
                    second = first;
                    first = num;
                } else if (num < first && num > second) {
                    second = num;
                }
            }
        }
        return second;
    }
};
 

复杂度分析
时间复杂度:O(n),其中 n 表示字符串的长度。我们只需遍历一遍字符串即可。
空间复杂度:O(1)。仅需常数个空间即可。
author:力扣官方题解










![[激光原理与应用-33]:典型激光器 -5- 不同激光器的全面、综合比较](https://img-blog.csdnimg.cn/img_convert/a6e952d1db2cb2738699cdd607c033a3.jpeg)







![[附源码]计算机毕业设计基于SpringBoot的酒店预订系统设计与实现](https://img-blog.csdnimg.cn/6c7f662fc2b343b9a9e335bef0271842.png)