【问题标题】:Most repeating character in a string字符串中重复最多的字符
【发布时间】:2013-11-03 23:10:05
【问题描述】:

给定一个字符串,例如取“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++;
    }
}

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

【问题讨论】:

  • "any ideas?" -- 一方面,更好地缩进和格式化您的代码,使其易于阅读。另一方面,考虑使用一个包含 26 个项目的数组,每个字母一个,并在相关插槽中设置最大连续计数。另一种选择是使用HashMap&lt;Character, Integer&gt;
  • 思路:首先找到所有重复的字符序列,然后寻找你找到的最大的。
  • 你会把大写和小写算作同一个字母吗?
  • 不,@keepcalmandcarryon

标签: java string


【解决方案1】:
let arr = [1,5,85,36,1,1,5,5,5,5,5,44]
let obj = {}
let newArr = []
let maxCount = 0
let maxChar = null
for(let i of arr){
    if(!obj[i]){
    obj[i] = 1
  }else{
    obj[i] ++
  }
  for(let j in obj){
    if(obj[j] > maxCount){
      maxCount = obj[j]
      maxChar = j
    }
  }
}
console.log(newArr, obj, maxCount, maxChar)

您可以使用此技术使用 javascript 来优化最大重复字符

【讨论】:

    【解决方案2】:

    简单但最好的实现如下。

     public static Character repeatingChar(String str) {
    
        char[] array = str.toCharArray();
    
        int max = 1;
        int count = 1;
        char ch = ' ';
        for (var i=1; i<str.length(); i++) {
            if (array[i] == array[i - 1])
                count++;
            else
                count =1;
            if (count > max) {
                max = count;
                ch = array[i - 1];
            }
    
        }
        return ch;
    }
    

    【讨论】:

    • 问题在于你如何看待它,这就是为什么你也有错误的问题。
    【解决方案3】:
        Simple way of finding Max character repetition
        ----------------------------------------------
        public char FindMaxRepeatedCharacter(string s)
        {
            Dictionary<char, int> keyValues = new Dictionary<char, int>();
            foreach(char c in s)
            {
                if (keyValues.ContainsKey(c))
                    keyValues[c]++;
                else
                    keyValues.Add(c, 1);
            }
    
            var maxValue =  keyValues.Values.Max();
            return keyValues.Where(x => x.Value == maxValue).FirstOrDefault().Key;
        }
    

    【讨论】:

    • 请提供详细描述。
    【解决方案4】:

    一个使用集合查找字符串中最大重复字符的简单程序。

    import java.util.Collection;
    import java.util.Collections;
    import java.util.HashMap;
    import java.util.Map;
    
    public class MaxCountOfString {
    
        public static <K, V> K getKey(Map<K, V> map, V val) {
            for (Map.Entry<K, V> each : map.entrySet()) {
                if (val.equals(each.getValue())) {
                    return each.getKey();
                }
            }
            return null;
        }
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            String lang = "malayalaaaaammmmmmmmmmmm";
            Map<Character, Integer> countmapper = new HashMap<>();
            int i = 0, j = 0;
            int count = 1;
            char[] ch = new char[lang.length()];
            for (int k = 0; k < ch.length; k++) {
                ch[k] = lang.charAt(k);
            }
            for (j = 0; j < lang.length(); j++) {
                count = 1;
                if (countmapper.containsKey(ch[j])) {
                    continue;
                } else {
                    for (i = j + 1; i < lang.length(); i++) {
                        if (lang.charAt(j) == ch[i]) {
                            count++;
    
                        }
                    }
                    if (!countmapper.containsKey(ch[j])) {
                        countmapper.put(lang.charAt(j), count);
                    }
                }
    
            }
    
            Collection<Integer> values = countmapper.values();
    
            System.out.println("The maximum repeated character from the string " + lang + " is :"
                    + getKey(countmapper, Collections.max(values)));
    
        }
    
    }
    

    【讨论】:

      【解决方案5】:

      返回输入字符串 SWIFT 中出现最多的字符

      let inputString = "testdsesatg"
      var tempDic : [Character: Int] = [:]     
              for char in inputString {
                  if tempDic[char] != nil {
                      tempDic[char] = tempDic[char]! + 1
                  }
                  else{
                      tempDic[char] = 1
                  }
              }
      

      我们检查字典值的最大计数

          let checkMax  = tempDic.max{ a, b in a.value < b.value}
          let sol = tempDic.keys.filter{ tempDic[$0] == checkMax?.value}
      

      这也将处理这种情况,如果在一个字符串中存在超过 1 个重复字符数相同且最大的字符

      【讨论】:

        【解决方案6】:
        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);
          }
        }
        

        【讨论】:

        • 虽然这个答案确实会有所帮助,但您还可以通过解释您所做的事情和原因来大大提高答案的质量。
        • 感谢您的宝贵意见,我已在代码中添加了 cmets,希望对您有所帮助,还有改进的余地,随时欢迎您!
        【解决方案7】:

        你可以试试这个代码:

        import java.util.Scanner;
        
        public class HighestOccuringConsecutiveChar 
        {
        
            public static char highestOccuringConsecutiveCharacter(String a) 
            {
                int c= 0, cNext = 0;
                char ans = '\0';
                for(int i = 0; i < a.length()-1; i++)
                {
                    if(a.charAt(i) == a.charAt(i+1))
                        cNext++;
        
                    if(cNext > c)
                    {
                        ans = a.charAt(i);
                        c = cNext;
                    }
                    if(a.charAt(i) != a.charAt(i))
                        cNext = 0;
                if(c == 0 && cNext == 0)
                    ans = a.charAt(i);
                }
                return ans;
            }
        
            public static void main(String[] args) 
            {
                Scanner s = new Scanner(System.in);     
                String str = new String();
                str = s.nextLine();     
                System.out.println(highestOccuringConsecutiveCharacter(str));
            }
        }
        

        【讨论】:

          【解决方案8】:
          public static char findMaximum(String input){
              int maxCount=0;
              int count=1;
              char result='\0';
              char[] temp=input.toCharArray();
              if(temp.length==1){
                  return temp[0];
              }
              for(int i=1;i<temp.length;i++){
                  if(temp[i]==temp[i-1]){
                      count++;
                  }
                  else{
                      if(count>maxCount){
                          maxCount=count;
                          result=temp[i-1];
                      }
                      count=1;
                  }
              }
              return result;
          
          }
          

          【讨论】:

          • 虽然这可能会回答 OP 的问题,但最好的答案是那些也包含解释的答案。您能否记录一下您的代码中发生了什么?
          【解决方案9】:
           import java.util.*;
              class findmax
              {
                  public static void main(String args[])
                      {
                          String s;
                          int max=0;
                          Scanner sc=new Scanner(System.in);
                          System.out.println("Enter String:");
                          s=sc.next();
                          String s1=" ";      
                          for(int i=0;i<s.length();i++)
                          {
                               int count=0;
                                  for(int j=i+1;j<s.length();j++){
                                      if(s.charAt(i)==s.charAt(j))
                                          count++;
                                  } 
                              if(count>max){
                                  s1=Character.toString(s.charAt(i));
                                  max=count;
                          }
                              else if(count==max)
                                  s1=s1+" "+Character.toString(s.charAt(i));
                          }
          
                          System.out.println(s1);
          
          
                      }
              }
          

          【讨论】:

            【解决方案10】:

            对于简单的字符串操作,这个程序可以这样完成:

            package abc;
            import java.io.*;
            
            public class highocc 
            {
                    public static void main(String args[])throws IOException
                    {
                        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                        System.out.println("Enter any word : ");
                        String str=in.readLine();
                        str=str.toLowerCase();
                        int g=0,count;
                        int ar[]=new int[26];
                        char ch[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
                            for(int i=0;i<ch.length;i++)
                            {
                                count=0;
                                for(int j=0;j<str.length();j++)
                                 {
                                    char ch1=str.charAt(j);
                                    if(ch[i]==ch1)
                                        count++;
                                 }
                               ar[i]=(int) count;
                            }
                            int max=ar[0];
                            for(int j=1;j<26;j++)
                            {
                                    if(max<ar[j])
                                    {
                                        max=ar[j];
                                        g=j;
                                    }
                                    else
                                    {
                                        max=ar[0];
                                        g=0;
                                    }
                            }
                            System.out.println("Maximum Occurence is "+max+" of character "+ch[g]);
                       } 
            }
            

            【讨论】:

              【解决方案11】:
              public static int findMaximumRepeatedChar(String str){
                     int count = 0, maxCount = 0, charAt = -1;                        
                     for(int i=0; i < str.length() - 1; i++){         
                        if(str.charAt(i) != str.charAt(i+1)){
                          if(count > maxCount){
                              maxCount = count;
                              charAt = i - count + 1;
                          }
                          count = 0;              
                      }else{
                          count++;
                      }           
                  }               
                  if(charAt == -1) return -1;
                  else return charAt;     
              }
              

              【讨论】:

                【解决方案12】:
                import java.util.*;
                
                public class HighestOccurence {
                
                    public static void getHighestDupsOccurrancesInString(char[] arr) {
                        int count = -1;
                        int max = 0;
                        Character result = ' ';
                        // Key is the alphabet and value is count
                        HashMap<Character, Integer> hmap = new HashMap<Character, Integer>();
                
                        for (int i = 0; i < arr.length; i++) {
                            if (hmap.containsKey(arr[i])) {
                                hmap.put(arr[i], hmap.get(arr[i]) + 1);
                            } else {
                                hmap.put(arr[i], 1);
                            }
                        }
                        for (Map.Entry<Character, Integer> itr : hmap.entrySet()) {
                            // System.out.println(itr.getKey() + " " + itr.getValue());
                            if (Integer.parseInt(itr.getValue().toString()) > max) {
                                max = Integer.parseInt(itr.getValue().toString());
                                if (hmap.containsValue(max)) {
                                    result = itr.getKey();
                                }
                            }
                        }
                        System.out.print("Maximum Occured Character is '" + result + "'");
                        System.out.print(" with count :" + max);
                
                    }
                
                    public static void main(String args[]) {
                
                        Scanner scan = new Scanner(System.in);
                        System.out.println("Enter the String");
                        String s = scan.nextLine();
                        if (s.trim().isEmpty()) {
                            System.out.println("String is empty");
                        } else {
                            char[] arr = s.toCharArray();
                            getHighestDupsOccurrancesInString(arr);
                        }
                
                    }
                
                }
                

                【讨论】:

                • 请不要添加代码。尝试添加解释。
                【解决方案13】:
                str = "AHSDFHLFHHSKSHDKDHDHHSJDKDKSDHHSDKKSDHHSDKLLDFLDFLDHAFLLLFFASHHHHHHYYYYYYYYYAAAAAAASDFJK"
                max = 1
                fin_max =1
                for i in range(0,len(str)-1):
                       if(str[i]==str[i+1]):
                           max = max + 1
                           if fin_max < max:
                              fin_max = max
                       else:
                           max = 1
                print fin_max
                

                【讨论】:

                  【解决方案14】:
                  private static void findMaxChar(string S)
                  {
                      char[] array = S.ToLower().ToCharArray();
                      int count = 1;
                      int max = 0;
                      char maxChar = '0';
                      for (int i = 0; i < S.Length-1; i++)
                      {  // Note that it should be S.length instead of S.length()
                          string stringleft=S.Replace(array[i].ToString(),"");
                          int countleft = S.Length - stringleft.Length;
                          count = countleft;
                          if (count > max)
                          {  // Record current run length, is it the maximum?
                              max = count;
                              maxChar = array[i];
                          }
                      }
                  
                      // This is to account for the last run
                      Console.WriteLine("Longest run: "+max+", for the character "+maxChar);
                  }
                  

                  【讨论】:

                  • 这只是代码的增强,可以在csharp中使用
                  【解决方案15】:

                  每次找到与前一个不同的字符,就意味着运行(连续重复的字母)结束,所以你应该记下当前运行的长度(即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.
                  

                  【讨论】:

                    【解决方案16】:

                    您可以使用三元运算符创建@justhalf 解决方案的简化版本。另外,如果使用 'charAt()' 方法,则不需要先将字符串转换为字符数组。

                    int  count   = 1;
                    int  max     = 1;
                    char maxChar = S.charAt(1);
                    
                    for(int i = 1; i < S.length(); i++) {
                        count = (S.charAt(i) == S.charAt(i - 1)) ? (count + 1) : 1;
                        if (count > max) {
                            max = count;
                            maxChar = S.charAt(i);
                        }
                    }
                    
                    System.out.println("Longest run: "+max+", for the character "+maxChar); 
                    

                    请注意,此代码假定 S 不为空。

                    【讨论】:

                      【解决方案17】:

                      请尝试我为我制作的这段代码............

                      public static String getMaxRepeatedChar(String txt) {
                              if ((txt != null)) {
                                  HashMap<Character, Integer> hash = new HashMap<Character, Integer>();
                                  char maxCh = 1;
                                  int maxCnt = 0;
                                  for (char ch : txt.toCharArray()) {
                                      if (hash.containsKey(ch)) {
                                          int i = hash.get(ch);
                                          hash.put(ch, i + 1);
                                          if (maxCnt < (i + 1)) {
                                              maxCh = ch;
                                              maxCnt = 1 + i;
                                          }
                      
                                      } else {
                                          hash.put(ch, 1);
                                          if (maxCnt < 1) {
                                              maxCh = ch;
                                              maxCnt = 1;
                                          }
                                      }
                      
                                  }
                                  return "Most Repeted character : " + maxCh + " and Count : "
                                          + maxCnt;
                              }
                      
                              return null;
                          }
                      

                      【讨论】:

                        【解决方案18】:

                        这是一个适用于所有字符的更通用的解决方案;字母数字或特殊,没关系。

                        private String findMaxChar(String str) {
                            char[] array = str.toCharArray();
                            int maxCount = 1;
                            char maxChar = array[0];
                            for(int i = 0, j = 0; i < str.length() - 1; i = j){
                                int count = 1;
                                while (++j < str.length() && array[i] == array[j]) {
                                    count++;
                                }
                                if (count > maxCount) {
                                    maxCount = count;
                                    maxChar = array[i];
                                }
                            }
                            return (maxChar + " = " + maxCount);
                        }
                        
                        System.out.println(findMaxChar("T"));
                        System.out.println(findMaxChar("TDD"));
                        System.out.println(findMaxChar("WWW"));
                        System.out.println(findMaxChar("NOREPEATS"));
                        System.out.println(findMaxChar("122333444455555"));
                        System.out.println(findMaxChar("abc33++$$$_###*ABCC"));
                        

                        输出

                        T = 1
                        D = 2
                        W = 3
                        N = 1 // First Character (if no repeats)
                        5 = 5
                        $ = 3
                        


                        如果要打印所有出现次数最多的字符,请使用Set 将它们收集为:
                        private static String findMaxChar(String str) {
                            char[] array = str.toCharArray();
                            Set<Character> maxChars = new LinkedHashSet<Character>();
                        
                            int maxCount = 1;
                            maxChars.add(array[0]);
                        
                            for(int i = 0, j = 0; i < str.length() - 1; i = j){
                                int count = 1;
                                while (++j < str.length() && array[i] == array[j]) {
                                    count++;
                                }
                                if (count > maxCount) {
                                    maxCount = count;
                                    maxChars.clear();
                                    maxChars.add(array[i]);
                                } else if (count == maxCount) {
                                    maxChars.add(array[i]);
                                }
                            }
                        
                            return (maxChars + " = " + maxCount);
                        }
                        

                        输出

                        [T] = 1
                        [D] = 2
                        [W] = 3
                        [N, O, R, E, P, A, T] = 1
                        [5] = 5
                        [$, #] = 3 // All Characters (in case of a tie)
                        

                        【讨论】:

                          【解决方案19】:

                          试试这个,

                                  char[] array = input.toCharArray();
                                  Arrays.sort(array);
                          
                                  int max = 0;
                                  int count = 1;
                                  char temp = array[0];
                                  for (char value : array)
                                  {
                                      if (value == temp)
                                      {
                                          count++;
                                      }
                                      else
                                      {
                                          temp = value;
                                          if (count > max)
                                          {
                                              max = count;
                                          }
                                          count = 1;
                                      }
                                  }
                          
                                  if(count > max)
                                  {
                                      max = count;
                                  }
                              System.out.println("count : "+max);
                          

                          【讨论】:

                            猜你喜欢
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            • 2015-03-17
                            • 2018-03-28
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            相关资源
                            最近更新 更多