Give you a mixed string s
, please return s
the second largest number, if there is no second largest number, please return -1
.
Mixed strings consist of lowercase English letters and numbers.
Example 1:
Input: s = "dfa12321afd" Output: 2 Explanation: The numbers appearing in s include [1, 2, 3]. The second largest number is 2 .
Example 2:
Input: s = "abc1111" Output: -1 Explanation: The numbers appearing in s only contain [1]. There is no second largest number.
hint:
1 <= s.length <= 500
s
Contains only lowercase English letters and/or numbers.
Analysis: The given string is a mixture, define two variables, fMax is the maximum value, sMax represents the second maximum value, we traverse it once, and need to judge that the corresponding character c is between '0' and '9' Between if(c>='0'&&c<='9'), if the condition is met, then we are judging whether it is greater than fMax, if((c-'0')>fMax), if the condition is met, first fMax = sMax, smax = c-'0',
If the condition is not met: judge whether c-'0' satisfies the (c-'0')<fMax&&(c-'0')>sMax condition, if so, assign it to the second largest value sMax = c-'0 ' ; Finally, we can return sMax
AC code:
class Solution {
public int secondHighest(String s) {
int fMax = -1 ;
int sMax = -1 ;
for(int i=0 ;i<s.length();i++){
char c = s.charAt(i);
if(c>='0'&&c<='9'){
if((c-'0')>fMax){
sMax = fMax ;
fMax = c-'0';
}else {
if((c-'0')<fMax&&(c-'0')>sMax){
sMax = c-'0' ;
}
}
}
}
return sMax ;
}
}