LeetCode 5693. The second largest number in a string (sorted)

Title:

给你一个混合字符串 s ,请你返回 s 中 第二大 的数字,如果不存在第二大的数字,请你返回 -1

混合字符串 由小写英文字母和数字组成。

数据范围:
1 <= s.length <= 500
s 只包含小写英文字母和(或)数字。

solution:

对串中的数字排序,取第二大即可,我用的桶排序.

code:

class Solution {
    
    
public:
    int secondHighest(string s) {
    
    
        int cnt[10]={
    
    0};
        for(auto i:s){
    
    
            if(isdigit(i)){
    
    
                cnt[i-'0']++;
            }
        }
        int f=0;
        for(int i=9;i>=0;i--){
    
    
            if(cnt[i])f++;
            if(f==2)return i;
        }
        return -1;
    }
};

Guess you like

Origin blog.csdn.net/weixin_44178736/article/details/115055363