大多数重复字符串中的字符 [英] Most repeating character in a string

查看:99
本文介绍了大多数重复字符串中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

We are given a string , for example, take "TUOPPPPJHHTT" We wish to find out which character occurs the most number of times CONTINUOUSLY in the string and how many times. In this case, its P occurring 4 times.

我尝试运行for循环,如下所示

I tried running a for loop as following

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

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

but in this approach, the problem is it will count repeated occurrences of all alphabets.

推荐答案

每次找到与前一个字符不同的字符时,就意味着运行(连续重复字母)结束了,所以你应该记下当前运行的长度(即 count 的值),然后重置计数。最后你可以打印最大值。

Each time you find different character than previous one, it means the run (consecutive repeating alphabet) is ended, and so you should note down the length of current run (i.e., the value of count) and then reset the count. At the end you can print the maximum.

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.

这篇关于大多数重复字符串中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆