题意:

image.png

解题思路:

  1. 思路:滑动窗口思想
  2. * [eceba]
  3. * 当数组大于2个,比如[e => 2, c => 1, b => 1]
  4. * 滑动数组:[e => 1, c => 1, b => 1] => [e => 1, c => 0, b => 1] => [e => 1, b => 1]

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param String $s
  4. * @return Integer
  5. */
  6. function lengthOfLongestSubstringTwoDistinct($s) {
  7. $n = strlen($s);
  8. if($n <= 2) return $n;
  9. $map = [];
  10. $j = 0; $len = 2;
  11. for ($i = 0; $i < $n; $i++){
  12. //分组
  13. ++$map[$s[$i]];
  14. //当数组大于2个,比如[e => 2, c => 1, b => 1]
  15. //滑动数组:[e => 1, c => 1, b => 1] => [e => 1, c => 0, b => 1] => [e => 1, b => 1]
  16. while (count($map) > 2) {
  17. $map[$s[$j]]--;
  18. if($map[$s[$j]] == 0) unset($map[$s[$j]]);
  19. $j++;
  20. }
  21. //更新长度
  22. if (count($map) <= 2) $len = max($len, array_sum($map));
  23. }
  24. return $len;
  25. }
  26. }