LeetCode 1796: Second Largest Digit in a String
Problem Description
Explanation
To solve this problem, we can iterate through the given string s
and keep track of the unique numerical digits we encounter. We can store these digits in a set to ensure uniqueness. Once we have all unique digits, we can sort them in descending order and return the second largest digit if it exists.
- Time complexity: O(n) where n is the length of the input string
s
. - Space complexity: O(1) since we are using a set to store at most 10 unique digits.
Solutions
class Solution {
public int secondHighest(String s) {
Set<Integer> digits = new HashSet<>();
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
digits.add(Character.getNumericValue(c));
}
}
List<Integer> sortedDigits = new ArrayList<>(digits);
Collections.sort(sortedDigits, Collections.reverseOrder());
if (sortedDigits.size() < 2) {
return -1;
}
return sortedDigits.get(1);
}
}
Loading editor...