1796. Second Largest Digit in a String
Description
Given an alphanumeric string s
, return the second 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:
Example 2:
Constraints:
1 <= s.length <= 500
s
consists of only lowercase English letters and/or digits.
Tags
String
Solution
This problem is similar to "find the second largest number", but requires the largest number is not equal to the second largest one. We initialize both the largest number first
and the 2nd largest number second
to -1. Iterave over the string and we only consider the case that the current character is a numeric byte/rune. We convert it from byte/rune to int type variable n
.
If
n > first
, we pass the value offirst
tosecond
, then assignn
tofirst
;If
n > second && n != first
, we only update the value ofsecond
withn
.
Finally, we return second
.
Complexity
Time complexity:
Space complexity:
Code
Last updated
Was this helpful?