美文网首页
【每日3题(1)】字符串中第二大的数字

【每日3题(1)】字符串中第二大的数字

作者: 程序员小2 | 来源:发表于2022-07-03 09:27 被阅读0次

    题目:

    给你一个混合字符串 s ,请你返回 s 中 第二大 的数字,如果不存在第二大的数字,请你返回 -1 。

    混合字符串 由小写英文字母和数字组成。

    示例 1:

    输入:s = "dfa12321afd"
    输出:2
    解释:出现在 s 中的数字包括 [1, 2, 3] 。第二大的数字是 2 。
    示例 2:

    输入:s = "abc1111"
    输出:-1
    解释:出现在 s 中的数字只包含 [1] 。没有第二大的数字。

    提示:

    1 <= s.length <= 500
    s 只包含小写英文字母和(或)数字。

    思路:

    此题比较简单,直接遍历,用两个变量记录第1大和第2大的数即可。

    java代码:

    class Solution {
        public int secondHighest(String s) {
            int firstMax = -1;
            int secondMax = -1;
    
            for(int i=0;i<s.length();i++) {
                char ch = s.charAt(i);
                if('0'<=ch && ch<='9') {
                    int num = ch-'0';
                    if(firstMax<num) {
                        secondMax = firstMax;
                        firstMax = num;
                    }else if(firstMax>num && secondMax<num) {
                        secondMax = num;
                    }
                }
            }
            return secondMax;
    
        }
    }
    

    相关文章

      网友评论

          本文标题:【每日3题(1)】字符串中第二大的数字

          本文链接:https://www.haomeiwen.com/subject/hllavrtx.html