zl程序教程

您现在的位置是:首页 >  后端

当前栏目

字符串中第二大的数字(遍历)

遍历 字符串 数字 第二
2023-09-11 14:15:14 时间

力扣链接:力扣

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

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

示例 1:

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

示例 2:

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

提示:

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

示例代码1: 【自己写】

class Solution:
    def secondHighest(self, s: str) -> int:
        num = []
        for i in s:
            if i.isdigit():
                num.append(i)
        num = list(set(num))
        if len(num) < 2:
            return -1
        else:
            num.remove(max(num))
            return int(max(num))

示例代码2:

class Solution:
    def secondHighest(self, s: str) -> int:
        a = b = -1
        for i in s:
            if i.isdigit():
                c = int(i)
                if c > a:
                    a, b = c, a
                elif b < c < a:
                    b = c
        return b

时间复杂度 O(n),空间复杂度 O(1)。其中 n 为字符串 s 的长度。

示例代码3:

class Solution:
    def secondHighest(self, s: str) -> int:
        count = 0
        for i in range(9, -1, -1):
            if str(i) in s:
                count += 1
                if count == 2:
                    return i
        return -1

        遍历9~0的降序数组,判断数字是否在字符串s中,同时用一个变量count维护遇到降序数字的次数.在已经遇到一个最大数字的情况下,再次遇到在字符串中的数字,即是第二大的数字.
如果遍历完数组仍然没有满足条件,则返回-1.