Skip to content

Latest commit

 

History

History
72 lines (61 loc) · 1.67 KB

1796. Second Largest Digit in a String.md

File metadata and controls

72 lines (61 loc) · 1.67 KB

the first one in Biweekly Contest 48.


Difficulty : Easy

Related Topics : String


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.

Solution

  • mine
    • Java
      • Runtime: 1 ms, faster than 100.00%, Memory Usage: 39.3 MB, less than 100.00% of Java online submissions
        // O(N)time
        // O(N)space
        public int secondHighest(String s) {
            char[] arr = s.toCharArray();
            int size = 0;
            int[] count = new int[10];
            for(int i = 0; i < arr.length; i++){
                if(arr[i] >= 'a') continue;
        
                int t = arr[i] - '0';
                if(count[t] == 0) size++;
                count[t]++;
            }
            if(size < 2) return -1;
            int t = 2;
            for(int i = count.length - 1; i >= 0; i--){
                if(count[i] != 0){
                    t--;
                }
                if(t == 0) return i;
            }
            return 0;
        }