题意:
解题思路:
思路:滑动窗口思想
* [eceba]
* 当数组大于2个,比如[e => 2, c => 1, b => 1]
* 滑动数组:[e => 1, c => 1, b => 1] => [e => 1, c => 0, b => 1] => [e => 1, b => 1]
PHP代码实现:
class Solution {
/**
* @param String $s
* @return Integer
*/
function lengthOfLongestSubstringTwoDistinct($s) {
$n = strlen($s);
if($n <= 2) return $n;
$map = [];
$j = 0; $len = 2;
for ($i = 0; $i < $n; $i++){
//分组
++$map[$s[$i]];
//当数组大于2个,比如[e => 2, c => 1, b => 1]
//滑动数组:[e => 1, c => 1, b => 1] => [e => 1, c => 0, b => 1] => [e => 1, b => 1]
while (count($map) > 2) {
$map[$s[$j]]--;
if($map[$s[$j]] == 0) unset($map[$s[$j]]);
$j++;
}
//更新长度
if (count($map) <= 2) $len = max($len, array_sum($map));
}
return $len;
}
}