<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!--
题目:
给你一个字符串 s ,字符串的「能量」定义为:只包含一种字符的最长非空子字符串的长度。请你返回字符串的能量。
示例 1:
输入:s = "leetcode"
输出:2
-->
<script>
// 1. 逐个扫描对比法
var maxPower = function(s) {
if(s.length<=1) return s.length
let maxLen = 1,len = 1,i=0
while(i<s.length-1) {
let curStr = s[i]
let preStr = s[i+1]
if(curStr===preStr) {
len++
}else {
len=1;
}
maxLen = Math.max(len,maxLen)
i++
}
return maxLen
};
console.log(maxPower('abbcccddddeeeeedcba')); //5
console.log(maxPower('')); //0
console.log('/');
// 2. 正则法
var maxPower2 = function(s) {
// 正则
// s为空 返回0
if (!s.length) { return 0; }
// /(\w|\s)\1+|\w/ 匹配重复的字符或单个字符 生成诸如这样的数组 ["a", "bb", "ccc", "dddd", "eeeee", "d", "c", "b", "a"]
var arr = s.match(/(\w|\s)\1+|\w/g);
// 求数组元素长度最大值
return Math.max(...arr.map(item => item.length));
}
console.log(maxPower2('leetcode')); //2
console.log('/');
// 3,滑动窗口法
/**
1).找到连续字符的起始下标[i,j),长度则为j-i;
2).用变量存放连续字符中的最大长度
3).返回最大长度
*/
var maxPower3 = function(s) {
let ans = 1;
let pos = 0;
for (let i = pos; i < s.length-1; i++) {
let j = i+1;
while (s[i] === s[j]) {
j++;
}
pos = j;
ans = Math.max(ans, j - i);
}
return ans;
}
console.log(maxPower3('leetcode')); //2
</script>
</body>
</html>