给你一个混合字符串 s ,请你返回 s 中 第二大 的数字,如果不存在第二大的数字,请你返回 -1 。
混合字符串 由小写英文字母和数字组成。
示例 1:
输入:s = "dfa12321afd"
输出:2
解释:出现在 s 中的数字包括 [1, 2, 3] 。第二大的数字是 2 。
示例 2:
输入:s = "abc1111"
输出:-1
解释:出现在 s 中的数字只包含 [1] 。没有第二大的数字。
提示:
1 <= s.length <= 500
s 只包含小写英文字母和(或)数字。
直接遍历字符串即可,不过需要关注一下初始值的问题:
int secondHighest(char * s){
int len = strlen(s);
int first_max = -1, second_max = -1;
for (int i = 0; i < len; i++) {
if (s[i] >= '0' && s[i] <= '9') {
if ((first_max > s[i] - '0') && (second_max < s[i] - '0')) {
second_max = s[i] - '0';
}
else if (first_max < s[i] - '0') {
second_max = first_max;
first_max = s[i] - '0';
}
}
}
return second_max;
}