Java 子阵列列表的大小不正确

Java 子阵列列表的大小不正确,java,arraylist,Java,Arraylist,经过艰苦的搜索,我仍然没有找到问题的正确答案,答案如下: 我必须编写一个java程序,输入字符串数组,并在其中找到相等元素的最大序列。如果多个序列具有相同的最长长度,则程序应打印其中最左边的序列。输入字符串以单行形式给出,用空格分隔 例如: 如果输入为:hi yes yes bye 输出应为:是 这是我的源代码: public static void main(String[] args) { System.out.println("Please enter a sequenc

经过艰苦的搜索,我仍然没有找到问题的正确答案,答案如下:

我必须编写一个java程序,输入字符串数组,并在其中找到相等元素的最大序列。如果多个序列具有相同的最长长度,则程序应打印其中最左边的序列。输入字符串以单行形式给出,用空格分隔

例如:

如果输入为:hi yes yes bye

输出应为:是

这是我的源代码:

public static void main(String[] args) {
    System.out.println("Please enter a sequence of strings separated by spaces:");
    
    Scanner inputStringScanner = new Scanner(System.in);
    
    String[] strings = inputStringScanner.nextLine().split(" ");
    System.out.println(String.join(" ", strings));
    
    ArrayList<ArrayList<String>> stringsSequencesCollection = new ArrayList<ArrayList<String>>();
    ArrayList<String> stringsSequences = new ArrayList<String>();
    stringsSequences.add(strings[0]);
    
      for (int i = 1; i < strings.length; i++) {
        if(strings[i].equals(strings[i - 1])) {
            stringsSequences.add(strings[i]);
        } else {
            
            System.out.println(stringsSequences + " " + stringsSequences.size());
            
            stringsSequencesCollection.add(stringsSequences);
            stringsSequences.clear();
            stringsSequences.add(strings[i]);
            
            //ystem.out.println("\n" + stringsSequences);
        }
        
        if(i == strings.length - 1) {
            stringsSequencesCollection.add(stringsSequences);
            stringsSequences.clear();
            
            System.out.println(stringsSequences + " " + stringsSequences.size());
        }
    }
    
    System.out.println(stringsSequencesCollection.size());
    System.out.println(stringsSequencesCollection.get(2).size());
    System.out.println();
    
    int maximalStringSequence = Integer.MIN_VALUE;
    int index = 0;
    ArrayList<String> currentStringSequence = new ArrayList<String>();
    
    for (int i = 0; i < stringsSequencesCollection.size(); i++) {
        currentStringSequence = stringsSequencesCollection.get(i);
        
        System.out.println(stringsSequencesCollection.get(i).size());
        
        if (stringsSequencesCollection.get(i).size() > maximalStringSequence) {
            maximalStringSequence = stringsSequencesCollection.get(i).size();
            index = i;
            //System.out.println("\n" + index);
        }
    }
    
    System.out.println(String.join(" ", stringsSequencesCollection.get(index)));
    

我认为这应该是正确的,但有一个问题-子数组列表的计数不正确:所有子数组列表的大小都是1,因此输出不正确。我不明白这是什么原因。如果有人能帮我修改代码,我将不胜感激

我认为这是相当直接的,只要在遍历阵列构建序列时跟踪最大序列长度即可

String input = "hi yes yes yes bye";
String sa[] = input.split(" ");
int maxseqlen = 1;
String last_sample = sa[0];
String longest_seq = last_sample;
int seqlen = 1;
String seq = last_sample;
for (int i = 1; i < sa.length; i++) {
    String sample = sa[i];
    if (sample.equals(last_sample)) {
        seqlen++;
        seq += " " + sample;
        if (seqlen > maxseqlen) {
            longest_seq = seq;
            maxseqlen = seqlen;
        }
    } else {
        seqlen = 1;
        seq = sample;
    }
    last_sample = sample;
}
System.out.println("longest_seq = " + longest_seq);
很多问题

首先,在处理列表的最后一个字符串时,在清除它之前实际上并没有打印它。应该是:

if(i == strings.length - 1)
  //...
  System.out.println(stringsSequences + " " + stringsSequences.size());      
  stringsSequences.clear();
这是输出中的错误

其次,也是最重要的一点,当您执行StringsSequenceCollection.add时,您正在添加一个对象,即对集合的引用。执行stringsSequences.clear后,会清空刚才添加的集合这是因为它不是复制,而是保留引用!。您可以通过在第一个循环完成后打印StringsSequenceCollection来验证这一点:它将包含3个空列表

那么我们如何做到这一点呢?首先,我们需要一个更合适的数据结构。我们将使用一个映射,对于每个字符串,它包含其最长序列的长度。由于我们也想管理领带,我们还将有另一个映射,它为每个字符串存储最长序列的最左端位置:

Map<String, Integer> lengths= new HashMap<>();
Map<String, Integer> indexes= new HashMap<>();
String[] split = input.split(" ");
lengths.put(split[0], 1);
indexes.put(split[0], 0);
int currentLength = 1;
int maxLength = 1;
for (int i = 1; i<split.length; i++) {
  String s = split[i];
  if (s.equals(split[i-1])) {
    currentLength++;
  }
  else {
    currentLength = 1;
  }

  int oldLength = lengths.getOrDefault(s, 0);
  if (currentLength > oldLength) {
    lengths.put(s, currentLength);
    indexes.put(s, i);
  }

  maxLength = Math.max(maxLength, currentLength);
}
//At this point, youll have in lengths a map from string -> maxSeqLengt, and in indexes a map from string -> indexes for the leftmost ending index of the longest sequence. Now we need to reason on those!
现在我们只需扫描序列最长的字符串:

//Find all strings with equal maximal length sequences
Set<String> longestStrings = new HashSet<>();
for (Map.Entry<String, Integer> e: lengths.entrySet()) {
  if (e.value == maxLength) { 
    longestStrings.add(e.key);
  } 
}

//Of those, search the one with minimal index
int minIndex = input.length();
String bestString = null;
for (String s: longestStrings) {
  int index = indexes.get(s);
  if (index < minIndex) {
    bestString = s;
  }
}
System.out.println(bestString);

下面的代码按预期输出结果:

public static void main(String[] args) {
        System.out.println("Please enter a sequence of strings separated by spaces:");

        Scanner inputStringScanner = new Scanner(System.in);

        String[] strings = inputStringScanner.nextLine().split(" ");
        System.out.println(String.join(" ", strings));

        List <ArrayList<String>> stringsSequencesCollection = new ArrayList<ArrayList<String>>();
        List <String> stringsSequences = new ArrayList<String>();
        //stringsSequences.add(strings[0]);
        boolean flag = false;
        for (int i = 1; i < strings.length; i++) {
            if(strings[i].equals(strings[i - 1])) {
                if(flag == false){
                stringsSequences.add(strings[i]);
                flag= true; 
                }
                stringsSequences.add(strings[i]);
            }
        }

        int maximalStringSequence = Integer.MIN_VALUE;
        int index = 0;
        List <String> currentStringSequence = new ArrayList<String>();
        for (int i = 0; i < stringsSequencesCollection.size(); i++) {
            currentStringSequence = stringsSequencesCollection.get(i);

            System.out.println(stringsSequencesCollection.get(i).size());

            if (stringsSequencesCollection.get(i).size() > maximalStringSequence) {
                maximalStringSequence = stringsSequencesCollection.get(i).size();
                index = i;
                //System.out.println("\n" + index);
            }
        }
        System.out.println(stringsSequences.toString());

我不明白你的问题。“子数组列表的计数不正确”是什么意思?或者更好,你所说的“子数组列表”是什么意思?换句话说:你的输入是什么?你的预期输出与实际输出是什么?我的输入是:hi yes yes yes By?你的预期输出是什么?您的实际输出是什么?我的输入是:hi yes yes bye输出应该是:yes yes yes我首先将输入记录在String[]strings变量中。然后我决定在arraylist变量stringsSequences中记录字符串的第一个元素。然后程序迭代字符串数组,如果它找到一个与前一个字符串相等的字符串,它将把它添加到StringsSequence中。否则程序将执行以下操作:1将stringSequences arrayList添加到二维arraList中;二清理;3将当前字符串添加到空字符串序列列表中。然后程序应比较ArrayList的大小,并获取并打印最大大小的数组列表:ArrayList currentStringSequence=new ArrayList;对于int i=0;imaximalStringSequence{maximalStringSequence=stringssequencecollection.geti.size;index=i;//System.out.println\n+index;}}感谢您的回答-我现在发现并纠正了我的错误:@RosenPetrov如果您对答案满意,请记住勾选正确以结束问题