Leetcode 1796. Second Largest Digit in a String
You are given an alphanumeric string s
. (Alphanumeric string is a string consisting of lowercase English letters and digits).
You have to find the second largest numerical digit that appears in s
. If it does not exist, return -1
.
s
?
-1
.-1
.import java.util.TreeSet;
public class SecondLargestDigit {
public int secondHighest(String s) {
// Using TreeSet to automatically sort the digits in natural order
TreeSet<Integer> digits = new TreeSet<>();
// Traverse the string
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
// Add the digit to the set
digits.add(Character.getNumericValue(c));
}
}
// Check if we have at least two distinct digits
if (digits.size() < 2) {
return -1;
}
// Remove the largest element
digits.pollLast();
// The next largest element is now the highest element in the set
return digits.last();
}
public static void main(String[] args) {
SecondLargestDigit solution = new SecondLargestDigit();
System.out.println(solution.secondHighest("dfa12321afd")); // Output: 2
System.out.println(solution.secondHighest("abc1111")); // Output: -1
}
}
This solution is efficient given the constraint of the string length up to 500 characters.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?