[= 滑动窗口 =]
题目描述
解题思路
思路一
1、计算字符串长度并遍历逐个字符并组装成新的字符串temp
2、判断当前字符是否存在于temp
3、存在:截取temp中第一个重复字符之前的字符串,剩余字符串重新赋值于temp
4、每次循环完成后计算前后两次temp长度max(-temp, +temp)
思路二:滑动窗口
1、初始左(left)右(right)窗棱都为0时,此时窗口(ans)最小
2、滑动开始:左窗棱暂时不动,右窗棱移动 right++ 直到超过字符串长度
3、 因为要获取最长不重复字符串,所以每次右窗棱(right)向右移动时判断当前字符串是否在出现在之前字符串中
4、借助hash map判重,用字符s[right]标识map的key,字符串下标(right)表示map的value
5、如果有重复,移动左窗棱(left):。注意:更新left不能比上一次小,更新map中重复元素的最新下标
解题方法
- PHP
// 思路一
function lengthOfLongestSubstring($s) {
// 例s='pwwek'
$temp = '';
$max = 0;
$len = strlen($s);
for ($i=0;$i<$len;$i++) {
$re = strpos($temp, $s[$i]);
$temp .= $s[$i]; // 先全部拼接 pww
if($re !== false) { // 有重复
$temp = substr($temp, $re+1); // pww->w
}
$max = max(strlen($temp), $max);
}
return $max;
}
- GO
// 思路二
func lengthOfLongestSubstring(s string) int {
strLen := len(s)
if strLen == 0 {
return 0
}
left,right,ans := 0,0,0
m := map[byte]int{}
for right < strLen{
if _,ok := m[s[right]]; !ok {
m[s[right]] = right
}else {
if m[s[right]] + 1 >= left {
left = m[s[right]] + 1
}
m[s[right]] = right
}
new := right-left+1
if (new > ans) {
ans = new
}
right ++
}
return ans
}
[= 字符串的排列 =]
题目描述(此题没有做出来,参考的官方题解) 😂😂😂
解题思路
解题方法
function checkInclusion($s1, $s2) {
$len_s1 = strlen($s1);
$len_s2 = strlen($s2);
// 如果s1字串大于s2字串 则直接返回false
if($len_s1 > $len_s2) return false;
// 滑动窗口,窗口内字串和s1中字符数量一致则true
$need = array_count_values(str_split($s1));
$neednums = count($need);
// 初始化窗口
$win = [];
foreach($need as $k=>$v) {
$win[$k] = 0;
}
// 窗口滑动
$left = 0;
$right = 0;
$find = 0;
while ($right < $len_s2) {
$temp = $s2[$right];
if(isset($need[$temp])) {
$win[$temp]++;
if($win[$temp] == $need[$temp]) {
$find++;
}
}
while ($find == $neednums) {
if($right-$left+1 == $len_s1) return true;
$tmp = $s2[$left];
if(isset($need[$tmp])) {
$win[$tmp]--;
if($win[$tmp] < $need[$tmp]) {
$find--;
}
}
$left++;
}
$right++;
}
return false;
}