Skip to content

Latest commit

 

History

History
121 lines (93 loc) · 3.62 KB

1796.md

File metadata and controls

121 lines (93 loc) · 3.62 KB
title description keywords
1796. 字符串中第二大的数字
LeetCode 1796. 字符串中第二大的数字题解,Second Largest Digit in a String,包含解题思路、复杂度分析以及完整的 JavaScript 代码实现。
LeetCode
1796. 字符串中第二大的数字
字符串中第二大的数字
Second Largest Digit in a String
解题思路
哈希表
字符串

1796. 字符串中第二大的数字

🟢 Easy  🔖  哈希表 字符串  🔗 力扣 LeetCode

题目

Given an alphanumeric string s, return _thesecond largest numerical digit that appears in _s , or-1 if it does not exist.

An alphanumeric**** string is a string consisting of lowercase English letters and digits.

Example 1:

Input: s = "dfa12321afd"

Output: 2

Explanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2.

Example 2:

Input: s = "abc1111"

Output: -1

Explanation: The digits that appear in s are [1]. There is no second largest digit.

Constraints:

  • 1 <= s.length <= 500
  • s consists of only lowercase English letters and digits.

题目大意

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

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

示例 1:

输入: s = "dfa12321afd"

输出: 2

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

示例 2:

输入: s = "abc1111"

输出: -1

解释: 出现在 s 中的数字只包含 [1] 。没有第二大的数字。

提示:

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

解题思路

  • 使用 max 来追踪最大数字,second 来追踪第二大的数字。
  • 遍历字符串,对于每个字符:
    • 如果该字符是数字(使用 isNaN(char) 来检查),将其转换为数字。
    • 如果数字等于当前的最大数字 max,跳过该字符。
    • 如果数字大于当前最大值 max,则更新 secondmax,然后更新 max
    • 如果数字小于 max 且大于 second,则更新 second
  • 遍历完成后,如果 second 仍然是初始值 -1,说明没有第二大的数字,返回 -1

复杂度分析

  • 时间复杂度O(n),其中 n 是字符串的长度,遍历字符串一次。
  • 空间复杂度O(1),用了常数空间来存储 maxsecond

代码

/**
 * @param {string} s
 * @return {number}
 */
var secondHighest = function (s) {
	let max = -1,
		second = -1;
	for (let char of s) {
		if (!isNaN(char)) {
			const num = Number(char);
			if (num == max) {
				continue;
			} else if (num > max) {
				second = max;
				max = num;
			} else if (num > second) {
				second = num;
			}
		}
	}
	return second;
};

相关题目

题号 标题 题解 标签 难度 力扣
2259 移除指定数字得到的最大结果 [✓] 贪心 字符串 枚举 🟢 🀄️ 🔗