【问题标题】:Alternate Solution for maxBlock from CodingBat来自 CodingBat 的 maxBlock 的替代解决方案
【发布时间】:2026-02-08 00:40:01
【问题描述】:

从codingBat解决this problem

给定一个字符串,返回其中最大“块”的长度 细绳。块是一系列相同的相邻字符。

maxBlock("hoopla") → 2
maxBlock("abbCCCddBBBxx") → 3
maxBlock("") → 0

我试图用一个for循环来解决它,如下所示:

public int maxBlock(String str) {
  int maxCounter=1;
  int counter=1;
  if(str.length()==0)
  {
    return 0;
  }  
  for(int i=0;i<str.length()-1;i++)
  {
    if(str.substring(i,i+1).equals(str.substring(i+1,i+2)))
    {
      counter++;

    }   
    if(counter>maxCounter)
    {
      maxCounter=counter;
      counter=0;
    }            
  }  


  return maxCounter;          
}

它击败了除一个之外的所有案例。任何人都可以展示一个带有一个 for 循环的解决方案吗?

抱歉迟到了,但您不能使用 REGEX 或集合框架中的任何内容。

【问题讨论】:

  • "它胜过所有案例,除了一个" > 这是什么意思?
  • 那么它在什么情况下失败了?
  • @Duncan maxBlock("XXBBBBbbxx") 应该返回 4 但我的解决方案返回 3。

标签: java


【解决方案1】:

我认为你在某些极端情况下弄错了:

public int yourMaxBlock(String str) {
    int maxCounter = 1;
    int counter = 1;
    if (str.length() == 0) {
        return 0;
    }
    for (int i = 0; i < str.length() - 1; i++) {
        if (str.substring(i, i + 1).equals(str.substring(i + 1, i + 2))) {
            counter++;

        }
        if (counter > maxCounter) {
            maxCounter = counter;
            counter = 0;
        }
    }

    return maxCounter;
}

public int myMaxBlock(String str) {
    int maxCounter = 1;
    int counter = 1;
    if (str.isEmpty()) {
        return 0;
    }
    for (int i = 1; i < str.length(); i++) {
        if (str.charAt(i - 1) == str.charAt(i)) {
            if (++counter > maxCounter) {
                maxCounter = counter;
            }
        } else {
            counter = 1;
        }
    }

    return maxCounter;
}

public void test() {
    String[] tests = new String[]{
        "", "+", "++", "+++,++,++,+", "+,++,+++,++,", "+,++,+++,++++", "+++++,++,+++,++++"
    };
    for (String s : tests) {
        int myMax = myMaxBlock(s);
        int yourMax = yourMaxBlock(s);
        System.out.println("myMaxBlock(" + s + ") = " + myMax + (myMax != yourMax ? " WRONG! you have " + yourMax : ""));
    }
}

打印

myMaxBlock() = 0
myMaxBlock(+) = 1
myMaxBlock(++) = 2
myMaxBlock(+++,++,++,+) = 3
myMaxBlock(+,++,+++,++,) = 3
myMaxBlock(+,++,+++,++++) = 4 WRONG! you have 3
myMaxBlock(+++++,++,+++,++++) = 5 WRONG! you have 4

【讨论】:

  • 谢谢@OldCurmudgeon 我看到你的解决方案有点晚了,但做得很好......你几乎整齐地纠正了我所缺少的。
【解决方案2】:

您可以使用模式匹配器"(.)(\\1)*" 在字符串中查找重复的字符,代码如下:

public int maxBlock(String str) {
        Pattern pattern = Pattern.compile("(.)(\\1)*");
        Matcher matcher = pattern.matcher(str);
        int max = 0;
        while (matcher.find()) {
            max = Math.max(max, matcher.group().length());
        }
        return max;
    }

【讨论】:

  • 这并没有真正解决以“任何人都可以用一个 for 循环显示解决方案吗?”结尾的问题。虽然仍然是一个有用的答案。
  • 之前没提过
【解决方案3】:

我参加聚会有点晚了,但这是我的 CodingBat 解决方案:

public int maxBlock(String str) {
    int max = 0;
    int count = 1;
    char o = ' ';

    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        if (c == o) {
            count++;
            if (count > max) { max = count; }
        } else {
            count = 1;
            if (count > max) { max = count; }
        }
        o = c;     
    }

    return max;
}

【讨论】:

    【解决方案4】:

    这是一个大致基于您的解决方案的解决方案。请注意使用charAt 以获得更整洁的代码示例。

    这从字符串的第二个字符开始,向后看是否仍然遇到相同的字符。如果是这样,则计数器增加。当我们完成一串相同字符时,我们会与目前找到的最大长度进行比较,并在必要时进行更新。

    public static int maxBlock(String str) {
        int maxCounter = 1;
        int counter = 1;
    
        if (str.length() == 0) {
            return 0;
        }
        for (int i = 1; i < str.length(); i++) {
            if (str.charAt(i - 1) == str.charAt(i)) {
                counter++;
            } else {
                // end of a run
                if (counter > maxCounter) {
                    maxCounter = counter;
                }
    
                counter = 1;
            }
    
        }
    
        return Math.max(maxCounter, counter);
    }
    

    【讨论】:

    • 在 maxBlock("xyzz") 它应该返回 2 但返回 1 时不起作用
    • @Anirudh 好点——上面做了一些调整。这现在通过了该网页上的测试。
    • @Anirudh OldCurmudgeon 的回答更简洁。我的 Math.max 位只是一个快速破解 :-)
    • 是的..这里实际上不需要使用2个循环..简单的代码更有效:-]
    【解决方案5】:

    只需使用一个 for 循环。我认为这是另一种方式。

    public int maxBlock(String str) {
      int len = str.length();
      int temp=(len>0)?1:0;
      int r =0;
    
      for(int i=1; i<len; i++){   
        if(str.charAt(i) == str.charAt(i-1)){
          temp++;   
        }
        else{
          r = (temp>r)?temp:r;
          temp=1;
        }
      }
      r = (temp>r)?temp:r;
      return r;
    }
    

    【讨论】:

      【解决方案6】:
      public int maxBlock(String str) {
      
          int max = 0;
      
          for(int i = 0 ; i < str.length() ; i ++ ) {
             char compareChar = str.charAt(i);
             int count = 0;
             while (i + 1 < str.length() 
                    && compareChar == str.charAt(i+1)) {
                 i++;
                 count ++;
            } 
      
            if (max < count + 1) {
               max = count + 1;
            }
         }
         return max;
      
      }
      

      【讨论】:

        【解决方案7】:

        这是我的解决方案。它比你想象的要简单。

        public int maxBlock(String str) 
        {
            //create a counter to return
            int counter = 0;
            //create a temporary variable to store a running total.
            int temp = 1;
            //Start on the first character and test to see if the second
            //character equals the first.
            for (int i = 1; i < str.length(); i++)
            {
              //If it does, we increment the temp variable.
              if (str.charAt(i) == str.charAt(i-1))
              {
                temp++;
              }
              //If it doesn't, we wipe the temp variable and start from one.
              else
              {
                temp = 1;
              }
              //If the temporary variable exceeds the counter amount, we make
              //the counter variable equal to the temp variable.
              if (temp > counter)
              {
                counter = temp;
              }
            }
            //Return the counter.
            return counter;
          }
        

        【讨论】:

          【解决方案8】:
          public int maxBlock(String str) {
          int maxLength = 0;
          Map<String,Integer> map = new HashMap<String,Integer>();
          for(int i = 0; i< str.length(); i++){
          String key = str.substring(i,i+1);
          if(i!=0 && str.charAt(i) == str.charAt(i-1) && map.containsKey(key)){
          map.put(key, map.get(key)+1);
          }
          else{
          map.put(key,1);
          }
          }
          
          for(Map.Entry<String,Integer> entry : map.entrySet()){
          if(maxLength <entry.getValue()){
          maxLength = entry.getValue();
          }
          }
          
          return maxLength;
          }
          

          【讨论】:

          • 请编辑该帖子,使其显示为代码,并添加代码说明。
          【解决方案9】:
          public int maxBlock(String str) {
          
              int count = 0;
              int i = 0;
              int maxcount = 0;
              if (str.length() == 0) return 0;
          
              while (i < str.length() - 1) {
          
                  if (str.charAt(i) == str.charAt(i + 1)) {
          
                      count++;
          
                      if (count > maxcount) {
                          maxcount = count;
                      }
                  } else count = 0;
          
                  i++;
              }
          
              return maxcount + 1;
          }
          

          【讨论】:

          • 这里是一个循环。
          【解决方案10】:
          public int maxBlock(String str) {
            int tcount = 0;
            if (str.length() < 1) {
              return 0;
            }
            for (int i = 0; i < str.length(); i++) {
              int count = 0;
              for (int j = i; j < str.length(); j++) {
                if (str.charAt(i) == str.charAt(j)) {
                  count++;
                } else
                  break;
              }
              if (count > tcount) {
                tcount = count;
              }
              i += count - 1;
          
            }
            return tcount;
          }
          

          这更容易,它完全有效。

          【讨论】:

            【解决方案11】:
            int i = 0;
            int j = 0;
            
            while(i < inner.length && j < outer.length) {
                    if(inner[i] > outer[j]) {
                        j++;
                    } else if(inner[i] < outer[j]) {
                        return false;
                    } else {
                        i++;
                    }
                }
            
                if(i != inner.length)
                    return false;
            
                return true;
            }
            

            【讨论】:

              【解决方案12】:

              这是我的代码

               public int maxBlock(String str) {
              
                int count = 1;
                for(int i=0;i<str.length()-1;i++){
                   int count2 = 0;
              
                   if(str.substring(i,i+1).equals(str.substring(i+1,i+2) )){
                     for(int j = i ; j < str.length();j++){
                        if(str.substring(i,i+1).equals(str.substring(j,j+1))){
                          ++count2;
                        }
                        else{
                          break;
                        }
                     }
                   }
              
                   if(count2 > count){
                     count = count2;
                   }
              
              
                }
              
                if(str.isEmpty())return 0;
                return count;
              }
              

              【讨论】: