我们给出了一个字符串,例如,取"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++;
}
}
Run Code Online (Sandbox Code Playgroud)
但在这种方法中,问题是它将计算所有字母表的重复出现次数.
每次找到与前一个字符不同的字符时,表示运行(连续重复字母表)结束,因此您应记下当前运行的长度(即值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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
41017 次 |
| 最近记录: |