【题目描述】
给你一个混合字符串 s
,请你返回 s
中 第二大 的数字,如果不存在第二大的数字,请你返回 -1
混合字符串 由小写英文字母和数字组成。
https://leetcode.cn/problems/second-largest-digit-in-a-string/description/
【代码】Leecode-set
package com.company;
// 2023-04-05;
import java.util.*;
class Solution {
public int secondHighest(String s) {
Set<Integer> set = new HashSet<>();
for (char c : s.toCharArray()){
if (Character.isDigit(c)){
// 字符转数字了
set.add(c - '0');
}
}
Object[] obj = set.stream().sorted().toArray();
return set.size() < 2 ? -1 : (int)obj[set.size() - 2];
}
}
public class Test {
public static void main(String[] args) {
new Solution().secondHighest("dfa12321afd"); // 输出:2
new Solution().secondHighest("abc1111"); // 输出:-1
new Solution().secondHighest("1a0"); // 输出:0
}
}
【代码】Leecode-一次遍历
package com.company;
// 2023-04-05;
import java.util.*;
class Solution {
public int secondHighest(String s) {
int mv1 = -1;
int mv2 = -1;
for (char c : s.toCharArray()){
int t = c - '0';
if (c < '0' || c > '9' || t == mv1) continue;
if (t > mv1) {
mv2 = mv1;
mv1 = t;
}else if ((t > mv2)){
mv2 = t;
}
}
return mv2;
}
}
public class Test {
public static void main(String[] args) {
new Solution().secondHighest("dfa12321afd"); // 输出:2
new Solution().secondHighest("abc1111"); // 输出:-1
new Solution().secondHighest("1a0"); // 输出:0
}
}
【代码】admin
思路:1. 去除所有的字符, 那么就只剩下数字了
2. 利用set去重, 排序
3. 把set转Object数组, 然后返回倒是第2个元素。如果单元素返回-1
package com.company;
// 2023-04-05;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
class Solution {
public int secondHighest(String s) {
if (s.length() == 1) return -1;
int num = 1;
s = s.replaceAll("[a-zA-Z]+", "");
Matcher matcher = Pattern.compile("\\d+").matcher(s);
if (matcher.find()){
String group = matcher.group();
char[] chars = group.toCharArray();
int[] res = new int[chars.length];
for (int i = 0; i < chars.length; i++){
res[i] = Character.getNumericValue(chars[i]);
}
Set<Integer> collect = Arrays.stream(res).boxed().sorted().collect(Collectors.toSet());
if (collect.size() == 1){
return -1;
}else {
Object[] objects = collect.toArray();
num = (int) objects[objects.length - 2];
}
}else {
return -1;
}
return num;
}
}
public class Test {
public static void main(String[] args) {
new Solution().secondHighest("dfa12321afd"); // 输出:2
new Solution().secondHighest("abc1111"); // 输出:-1
new Solution().secondHighest("1a0"); // 输出:0
}
}