class Solution:
def secondHighest(self, s: str) -> int:
digits = set()
for ch in s:
if ch.isdigit():
digits.add(int(ch))
if len(digits) < 2:
return -1
return sorted(digits, reverse=True)[1]
class Solution {
public:
int secondHighest(string s) {
set<int> digits;
for (char ch : s) {
if (isdigit(ch)) {
digits.insert(ch - '0');
}
}
if (digits.size() < 2) return -1;
auto it = digits.rbegin();
++it;
return *it;
}
};
class Solution {
public int secondHighest(String s) {
Set<Integer> digits = new HashSet<>();
for (char ch : s.toCharArray()) {
if (Character.isDigit(ch)) {
digits.add(ch - '0');
}
}
if (digits.size() < 2) return -1;
List<Integer> list = new ArrayList<>(digits);
Collections.sort(list, Collections.reverseOrder());
return list.get(1);
}
}
var secondHighest = function(s) {
let digits = new Set();
for (let ch of s) {
if (ch >= '0' && ch <= '9') {
digits.add(Number(ch));
}
}
if (digits.size < 2) return -1;
let arr = Array.from(digits).sort((a, b) => b - a);
return arr[1];
};
Given a string s
that consists of lowercase English letters and digits, your task is to return the second largest numerical digit that appears in s
. If there is no such digit, return -1
.
-1
.The problem asks us to find the second largest digit in a string. At first glance, we might think about scanning the string, collecting the digits, and then somehow figuring out which is the second largest. A brute-force approach could involve storing all digits, sorting them, and picking the second largest. But we can do better by using a set to avoid duplicates and only keeping track of unique digits. This reduces unnecessary work and makes our solution more efficient.
The key insight is to recognize that we only care about unique digits, and their order from largest to smallest. We don't need to store the entire string or worry about letter characters at all.
Here is a step-by-step guide to solving the problem efficiently:
s
, check if it's a digit. If so, convert it to an integer and add it to the set.-1
because there is no second largest digit.This approach is efficient because:
Let's work through an example with s = "dfa12321afd"
:
If the input was "abc1111"
, the set would be {1}, so we return -1.
To solve the "Second Largest Digit in a String" problem, we scan the string and collect unique digits using a set. After ensuring there are at least two unique digits, we sort them and return the second largest. This approach is efficient, simple, and leverages the properties of sets and the limited range of digits, making it both elegant and practical for this task.