# 1796. Second Largest Digit in a String¶

• Time: $O(n)$
• Space: $O(1)$
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 class Solution { public: int secondHighest(string s) { int maxDigit = -1; int secondMaxDigit = -1; for (const char c : s) if (isdigit(c)) { const int digit = c - '0'; if (digit > maxDigit) { secondMaxDigit = maxDigit; maxDigit = digit; } else if (maxDigit > digit && digit > secondMaxDigit) { secondMaxDigit = digit; } } return secondMaxDigit; } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Solution { public int secondHighest(String s) { int maxDigit = -1; int secondMaxDigit = -1; for (final char c : s.toCharArray()) if (Character.isDigit(c)) { final int digit = Character.getNumericValue(c); if (digit > maxDigit) { secondMaxDigit = maxDigit; maxDigit = digit; } else if (maxDigit > digit && digit > secondMaxDigit) { secondMaxDigit = digit; } } return secondMaxDigit; } } 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Solution: def secondHighest(self, s: str) -> int: maxDigit = -1 secondMaxDigit = -1 for c in s: if c.isdigit(): d = int(c) if d > maxDigit: secondMaxDigit = maxDigit maxDigit = d elif maxDigit > d > secondMaxDigit: secondMaxDigit = d return secondMaxDigit