1796. 字符串中第二大的数字
给你一个混合字符串 s
,请你返回 s
中 第二大 的数字,如果不存在第二大的数字,请你返回 -1
。
混合字符串 由小写英文字母和数字组成。
示例1:
输入:s = "dfa12321afd" 输出:2 解释:出现在 s 中的数字包括 [1, 2, 3] 。第二大的数字是 2 。
示例 2:
输入:s = "abc1111" 输出:-1 解释:出现在 s 中的数字只包含 [1] 。没有第二大的数字。
提示:
1 <= s.length <= 500
s
只包含小写英文字母和(或)数字。
我的答案是这样的:
class Solution {
public int secondHighest(String s) {
int n = s.length();
int max = -1, nextMax = -1;
for (int i = 0; i < n; i++) {
if (s.charAt(i) <= '9' && s.charAt(i) >= '0') {
int data = s.charAt(i) - '0';
System.out.println(data);
if (max < data) {
nextMax = max;
max = data;
}else if (nextMax < data && max > data){
nextMax = data;
}
System.out.println(max + "," + nextMax);
}
}
return nextMax;
}
}
复杂度分析
时间复杂度:O(n),其中 n 是数组 points的长度。
空间复杂度:O(1)。
其中有一个知识点,可以让代码更简单,这个函数是直接判断字符是否为字母
Character.isDigit(ch)
今日一题已完成 明天会更好