打印设置了最重复字符的子字符串



例如 1:如果我有这样的数字 1 2 3 4 1 3 4 5 6 1 4 5 6 2 1 2

它应该打印1 2 3 4 1 3 4 5 6 1 4 5 6 2 1因为 1 来了 4 次

例如 2: 2 3 4 2 2 1 3 4 5 6 7

它应该打印2 3 4 2 2因为它具有最大出现次数

我知道我们必须找到最大出现数字的基本方法,然后我们必须在输入数组中搜索该数字的开始和最后一个索引并打印它。

如果可能的话,我想要任何其他更好的方法。

  • 对于字符串中的每个字符,维护计数,以及它在Map<Character,FirstAndLast>中第一次和最后一次出现的索引(见下文)
  • 地图完成后,遍历其值,然后选择count最高的值;选择解决关系的策略
  • 取一个介于firstlast(包括 )之间的子字符串,作为具有最大count的值。

FirstAndLast是表示一对整数的简单对象:

class FirstAndLast {
private int first, last, count;
public FirstAndLast(int index) { first = last = index; count = 1;}
public int getFirst() { return first; }
public int getLast() { return last; }
public int getCount() { return count; }
public void setFirst(int index) { first = index; }
public void setLast(int index) { last = index; }
public void incrementCount() { count++; }
}

最新更新