Skip to content

Commit 21a855c

Browse files
authored
Create 1796-second-largest-digit-in-a-string.java
1 parent 8f0aa6d commit 21a855c

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Problem: 1796. Second Largest Digit in a String
3+
* Difficulty: Easy
4+
* URL: https://leetcode.com/problems/second-largest-digit-in-a-string/
5+
*
6+
* Approach:
7+
* - Track the maximum and second maximum digits found while iterating.
8+
* - Update second maximum when a new maximum appears or when finding a digit between them.
9+
*
10+
* Time Complexity: O(n) // scan string once
11+
* Space Complexity: O(1) // only a few integer variables
12+
*/
13+
14+
class Solution {
15+
public int secondHighest(String s) {
16+
int max = -1;
17+
int sMax = -1;
18+
19+
for (char ch : s.toCharArray()) {
20+
if (Character.isDigit(ch)) {
21+
int num = ch - '0';
22+
if (num > max) {
23+
sMax = max;
24+
max = num;
25+
} else if (num < max && num > sMax) {
26+
sMax = num;
27+
}
28+
}
29+
}
30+
return sMax;
31+
}
32+
}

0 commit comments

Comments
 (0)