算法学习记录005_寻找字符串中连续最长字符以及个数
作者:互联网
一、寻找最长
<script>
function count(str){
let i = 0;
let j = 0;
let maxChar = '';
let maxCount = 0;
while(i<str.length){
//当i指向的元素与j指向的元素不相等的时候,说明字符发生了变化
if(str[i]!=str[j]){
let count = j-i
//当前变化次数大于上一次时,修改最大次数以及出现最多的字符
if(count>maxCount){
maxCount = count
maxChar = str[i]
}
i=j;
}
j++;
}
console.log("连续出现次数最多的字符是::"+maxChar,"出现次数为::"+maxCount)
}
count('aaabbbbbbcccccccccccdddddddfffffffff1112')
</script>
二、寻找最短
public class SuanFa {
public static void main(String[] args) {
count("aaabbbbcccccccccccc");
}
public static void count(String str) {
int i = 0;
int j = 0;
int maxCount = str.length();
String maxChar = "";
while (i < str.length()) {
if (j == str.length() || str.charAt(i) != str.charAt(j)) {
int count = j - i;
if (count <= maxCount) {
maxCount = count;
maxChar = str.charAt(i) + "";
}
i = j;
}
j++;
}
System.out.println("连续出现次数最少的字符是::" + maxChar + ",出现次数为::" + maxCount);
}
}
标签:count,maxChar,005,int,个数,算法,let,str,maxCount 来源: https://blog.csdn.net/Duckdan/article/details/118605680