根据以下说明查找字符串数组的模式?

问题描述 投票:0回答:1

实现一个称为mostCommonWordLength()的方法。它在列表中找到模式。如果有最高模式的约束,则返回-1。

public class Mode{
public static void main(String[] args){

    String[] list = {"a" , "as", "asd", "asdf", "asdfg", "asdfh", "asdfgh", "asdfgj" };

    System.out.println(" Mode is " + mostCommonWordLength(list));
}

private static int mostCommonWordLength(String[] words) {          

    int maxModeCount = 0; //  overall mode count
    int secondHighestModeCount = 0; 
    int maxMode = 0; // overall mode
    int secondHighestMode = 0; 

    for(int i = 0; i < words.length; i ++){ // iteration to test each value with each other

      int count = 0;// the count in this iteration

      for(int j = 1; j < words.length; j++ ){

        if(words[i].length() == words[j].length()){ // increase count if same length
          count++;
        }
      }

      if(count > maxModeCount){ // if the current count is greater than overall. update the mode count and mod value
        maxModeCount = count;
        maxMode = words[i].length();
      }
    }  
    return maxModeCount;
    /* 

    for(int i = 0; i < words.length; i ++){ // iteration to test for secondHighestMode

        int count = 0;// the count in this iteration

        for(int j = 0; j < words.length; j++ ){

          if(words[i].length() == words[j].length()){ // increase count if same length
            count++;
          }
        }

        if(count > secondHighestModeCount && count< maxModeCount){ // if the current count is greater than overall. update the mode count and mod value
          secondHighestModeCount = count;
          secondHighestMode = words[i].length();
        }            
      } 
      if(secondHighestModeCount == maxModeCount){
        return -1;
      }
      else{
          return maxModeCount;
      }
      */    
 }                   

}

所以基本上我现在遇到的问题是我拥有的列表,但找不到maxMode。输出说的是2。我还注释掉嵌套在循环中的部分,因为它找不到maxMode。一旦解决,两个循环就起作用。输出应为-1。

java arrays string mode
1个回答
0
投票

问题是:

  1. 在示例列表中,最大模式为2,长度5和6都出现。由于没有检查领带,代码实质上返回2。领带的代码可能是,

    if (count > 0 && count == maxModeCount){ return -1}

  2. 给定函数名称,您的代码应返回maxMode

  3. 如果您的嵌套循环正在成对检查,​​则内部循环应为

    for(int j = 0; j < words.length && j!=i ; j++ ){

    for(int j = i+1; j < words.length; j++ ){

© www.soinside.com 2019 - 2024. All rights reserved.