File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments