华为OD机试-去除多余字符后剩余最大值

 

 

import java.util.*;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {
        String source = "34533";
        String[] source_copy = source.split("");
        // 获取待删除的字符
        List<String> collect = Arrays.stream(source_copy).collect(Collectors.groupingBy(Objects::toString, Collectors.counting())).entrySet().stream().filter(stringLongEntry -> stringLongEntry.getValue() > 2).map(Map.Entry::getKey).sorted(Comparator.comparingInt(Integer::valueOf)).collect(Collectors.toList());
        collect.forEach(currentChar -> {
            ArrayList<Integer> idx = new ArrayList<>();
            int currentIdx = 0;
            // 找到所在的位置
            while (true) {
                int i = source.indexOf(currentChar, currentIdx);
                if (i == -1) break;
                idx.add(i);
                currentIdx = i + 1;
            }
            // 计算需要删除的次数
            int deleteCount = idx.size() - 2;

            // 执行删除
            for (Integer integer : idx) {
                if (integer == source.length() - 1) {
                    break;
                }
                if (source.charAt(integer) < source.charAt(integer + 1)) {
                    source_copy[integer] = "";
                    deleteCount--;
                    if (deleteCount == 0) break;
                }
            }

            // 如果上轮没有找到合适的
            if (deleteCount != 0) {
                do {
                    if (Integer.parseInt(currentChar) == 9) {
                        source_copy[source.indexOf(currentChar)] = "";
                    } else {
                        source_copy[source.lastIndexOf(currentChar)] = "";
                    }
                    deleteCount--;
                } while (deleteCount != 0);
            }
        });

        System.out.println(String.join("", source_copy));

    }


}

 

posted @ 2023-08-14 00:25  手握钢叉的猹  阅读(10)  评论(0编辑  收藏  举报