Java 字符串中重复次数最多的字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19579568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Most repeating character in a string
提问by AmanArora
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.
给定一个字符串,例如,取“TUOPPPPJHHTT”我们希望找出字符串中连续出现次数最多的字符以及出现的次数。在这种情况下,它的 P 出现了 4 次。
I tried running a for loop as following
我尝试运行一个 for 循环如下
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.
但在这种方法中,问题在于它会计算所有字母的重复出现次数。
采纳答案by justhalf
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.
每次发现与前一个不同的字符时,就意味着运行(连续重复字母)结束,因此您应该记下当前运行的长度(即 的值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.
回答by newuser
Try this,
尝试这个,
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);
回答by Ravi Thapliyal
Here's a more generic solution that works for allcharacters; alphanumeric or special, doesn't matter.
这是一个适用于所有角色的更通用的解决方案;字母数字或特殊,无关紧要。
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"));
Output:
输出:
T = 1
D = 2
W = 3
N = 1 // First Character (if no repeats)
5 = 5
$ = 3
如果要打印出现次数最多的所有字符,请使用 a
Set
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);
}
Output:
输出:
[T] = 1
[D] = 2
[W] = 3
[N, O, R, E, P, A, T] = 1
[5] = 5
[$, #] = 3 // All Characters (in case of a tie)
回答by Manmohan Soni
Please try this code i made it for me.........
请试试我为我做的这个代码.........
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;
}
回答by ptdecker
You can use the ternary operator to create a simplified version of @justhalf's solution. Plus, you don't need to convert the string to a character array first if you use the 'charAt()' method.
您可以使用三元运算符来创建@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);
Note that this code assumes S is not empty.
请注意,此代码假定 S 不为空。
回答by Ashwani Sharma
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);
}
回答by Rajesh
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
回答by Minnie
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);
}
}
}
回答by Amal Singam
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;
}
回答by Amit Sahay
For Simple String Manipulation, this program can be done as:
对于简单的字符串操作,这个程序可以这样完成:
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]);
}
}