We need to find the second largest digit in the string. We can collect all digits, sort or track the two largest, and return the second largest if it exists.
import java.util.*;
classSolution {
publicintsecondHighest(String s) {
TreeSet<Integer> set =new TreeSet<>();
for (char c : s.toCharArray())
if (Character.isDigit(c)) set.add(c -'0');
if (set.size() < 2) return-1;
set.pollLast();
return set.last();
}
}
1
2
3
4
5
6
7
classSolution {
funsecondHighest(s: String): Int {
val set = sortedSetOf<Int>()
for (c in s) if (c.isDigit()) set.add(c - '0')
returnif (set.size < 2) -1elseset.elementAt(set.size - 2)
}
}
1
2
3
4
5
defsecondHighest(s: str) -> int:
digits = {int(c) for c in s if c.isdigit()}
if len(digits) <2:
return-1return sorted(digits)[-2]
1
2
3
4
5
6
7
8
9
10
11
12
use std::collections::BTreeSet;
pubfnsecond_highest(s: String) -> i32 {
letmut set = BTreeSet::new();
for c in s.chars() {
if c.is_ascii_digit() {
set.insert(c asu8-b'0');
}
}
if set.len() <2 { return-1; }
letmut v: Vec<_>= set.into_iter().collect();
v[v.len()-2] asi32}
1
2
3
4
5
6
functionsecondHighest(s: string):number {
constdigits=newSet<number>();
for (constcofs) if (c>='0'&&c<='9') digits.add(Number(c));
if (digits.size<2) return-1;
return [...digits].sort((a, b) =>a-b)[digits.size-2];
}