简体   繁体   English

查找最长且包含最低可能数字的字符串的算法?

[英]Algorithm to find string which is longest and contains lowest possible numbers?

I have to find string out of these which is longest and contains the lowest possible numbers.我必须从这些字符串中找到最长且包含尽可能少的数字的字符串。

  1. 10,20 10,20
  2. 10,20,30 10,20,30
  3. 10,30,40 10,30,40
  4. 30,40,50 30,40,50

Ans 10,20,30答案 10,20,30

I am trying to think of algorithm which can be used to find such record.我正在尝试考虑可用于查找此类记录的算法。

Record will not contain duplicate number for example e.g 10,10,20 won't be case.

Based on clarification of requirements:在明确要求的基础上:

  • split strings by delimiters and convert to lists of (unique) numbers通过分隔符拆分字符串并转换为(唯一)数字列表
  • determine the max # of elements, M, in any list确定任何列表中的最大元素数 M
  • get the set of lists with M elements获取包含 M 个元素的列表集
  • for each list, find the min element对于每个列表,找到最小元素
  • pick the list with the lowest min选择最小值最低的列表

There is a general solution for problems where you need to find a string out of a collection of strings.对于需要从字符串集合中查找字符串的问题,有一个通用解决方案。

In case your data can be sorted then use a PriorityQueue .如果您的数据可以排序,请使用PriorityQueue

From the docs:从文档:

An unbounded priority queue based on a priority heap.基于优先级堆的无界优先级队列。 The elements of the priority queue are ordered according to their natural ordering, or by a Comparator优先级队列的元素根据它们的自然顺序或通过比较器进行排序

    PriorityQueue<String> a = new PriorityQueue<>((o1, o2) -> {
        int compare = Integer.compare(o1.length(), o2.length());
        if(compare != 0){
            return compare;
        }
        
        int result = compare numbers...

        return result;
    });

    a.add("10,20");
    a.add("10,20,30");
    a.add("10,30,40");
    a.add("30,40,50");

    System.out.println(a.remove()); // 10,20,30

In case it's not, use any List and do the filtering one by one.如果不是,请使用任何列表并一一进行过滤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM