Skip to content

Latest commit

 

History

History
85 lines (65 loc) · 2.38 KB

File metadata and controls

85 lines (65 loc) · 2.38 KB

中文文档

Description

Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist.

An alphanumeric string is a string consisting of lowercase English letters and digits.

 

Example 1:

Input: s = "dfa12321afd"
Output: 2
Explanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2.

Example 2:

Input: s = "abc1111"
Output: -1
Explanation: The digits that appear in s are [1]. There is no second largest digit. 

 

Constraints:

  • 1 <= s.length <= 500
  • s consists of only lowercase English letters and/or digits.

Solutions

Python3

class Solution:
    def secondHighest(self, s: str) -> int:
        largest_digit = second_largest_digit = -1
        for c in s:
            if c.isdigit():
                num = int(c)
                if num > largest_digit:
                    second_largest_digit, largest_digit = largest_digit, num
                elif num > second_largest_digit and num < largest_digit:
                    second_largest_digit = num
        return second_largest_digit

Java

class Solution {
    public int secondHighest(String s) {
        int largestDigit = -1, secondLargestDigit = -1;
        for (int i = 0; i < s.length(); ++i) {
            char c = s.charAt(i);
            if (c >= '0' && c <= '9') {
                int num = c - '0';
                if (num > largestDigit) {
                    secondLargestDigit = largestDigit;
                    largestDigit = num;
                } else if (num > secondLargestDigit && num < largestDigit) {
                    secondLargestDigit = num;
                }
            }
        }
        return secondLargestDigit;
    }
}

...