字符串中重复次数最多的字符

新手上路,请多包涵

给定一个字符串,例如,取“TUOPPPPJHHTT”,我们希望找出哪个字符在字符串中连续出现的次数最多,出现了多少次。在这种情况下,它的 P 出现了 4 次。

我尝试如下运行 for 循环

char[] array = S.toCharArray();
int count=1;
for(int i =1; i < S.length(); i++) {
    if(array[i] == array[i-1]) {
        count++;
    }
}

但在这种方法中,问题是它将计算所有字母的重复出现次数。

原文由 AmanArora 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 834
2 个回答

每次发现与上一个不同的字符时,就意味着运行(连续重复字母)结束,因此您应该记下当前运行的长度(即 count 的值),然后重新设置伯爵。最后你可以打印最大值。

 char[] array = S.toCharArray()
int count = 1;
int max = 0;
char maxChar = 0;
for(int i=1; i<array.length; i++){ // Start from 1 since we want to compare it with the char in index 0
    if(array[i]==array[i-1]){
        count++;
    } else {
        if(count>max){  // Record current run length, is it the maximum?
            max=count;
            maxChar=array[i-1];
        }
        count = 1; // Reset the count
    }
}
if(count>max){
    max=count; // This is to account for the last run
    maxChar=array[array.length-1];
}
System.out.println("Longest run: "+max+", for the character "+maxChar); // Print the maximum.

原文由 justhalf 发布,翻译遵循 CC BY-SA 3.0 许可协议

package naresh.java;

import java.util.HashMap;
import java.util.Map;

public class StringPrg {
  public static void main(String args[]){
    String str= "Ramrrnarmmmesh";
    //using hashmap to store unique character with integer count
    Map<Character,Integer> map1 = new HashMap<Character,Integer>();

    for(int k=0; k < str.length(); k++)
    {
      char currentChar = str.charAt(k);
      //to check that currentChar is not in map, if not will add 1 count for firsttime
      if(map1.get(currentChar) == null){
        map1.put(currentChar, 1);
      }
      /*If it is repeating then simply we will increase the count of that key(character) by 1*/
      else {
        map1.put(currentChar, map1.get(currentChar) + 1);
      }
    }
    //Now To find the highest character repeated
    int max=0;
    char maxCharacter = 'a';//setting to a by default
    for (Map.Entry<Character, Integer> entry : map1.entrySet())
    {
        System.out.println("Key=" + entry.getKey() + ":Value" + entry.getValue());
        if(max<entry.getValue()){
            max=entry.getValue();
            maxCharacter=entry.getKey();
      }
    }
    System.out.println("Max Character=" + maxCharacter + "Max Count" + max);
  }
}

原文由 Ramnaresh Mantri 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题