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.
Approach
C++
#include <bits/stdc++.h>using namespace std;int secondHighest(string s){int n = s.size();int i = 0;set<int> st;while (i < n){while (i < n && !(s[i] >= '0' && s[i] <= '9'))i++;while (i < n && s[i] >= '0' && s[i] <= '9'){st.insert(s[i] - '0');i++;}}if (st.size() >= 2){vector<int> vec;for (auto it = st.begin(); it != st.end(); it++)vec.push_back(*it);sort(vec.begin(), vec.end());return vec[vec.size() - 2];}return -1;}int main(){string s = "dfa12321afd";cout << secondHighest(s) << "\n";return 0;}
No comments:
Post a Comment