给你一个混合字符串 s ,请你返回 s 中 第二大 的数字,如果不存在第二大的数字,请你返回 -1 。
混合字符串 由小写英文字母和数字组成。
示例 1:
输入:s = "dfa12321afd"
输出:2
解释:出现在 s 中的数字包括 [1, 2, 3] 。第二大的数字是 2 。
这里我们使用2种思路来解决上述问题:第一种使用max和secondMax来解决,secondMax代表第二大;第二种使用一个数组,然后从后往前遍历。
解决思路:
代码实现如下:
class Solution {public int secondHighest(String s) {char[] arr = s.toCharArray();int max = -1;int secondMax = -1;for (char c : arr) {if (Character.isDigit(c)) {if (max < (c - '0')) {secondMax = max;max = c - '0';} else if(max > (c - '0')) {secondMax = Math.max(secondMax, c - '0');}}}return secondMax;}
}
解决思路:
public int secondHighest(String s) {int[] value = new int[10];for (char c : s.toCharArray()) {if (c >= '0' && c <= '9') {value[c - '0']++;}}int count = 0;for (int i = 9; i >= 0; i--) {if (value[i] > 0) {count++;}if (count >= 2) {return i;}}return -1;}
这里我们用了2种解法,第一种解法是标准解决方法,思路明确;第二种解法有些取巧的感觉,但是给我们提供了一套新的思路,并且执行效率也特别高。