当前位置: 首页 > 后端技术 > PHP

LeetCodePHP题解3.无重复字符的最长子串

时间:2023-03-29 19:08:51 PHP

题目链接3.longest-substring-without-repeating-characters难度:中知识点1.滑动窗口法经典算法,解法在此不展开1.暴力循环2.滑动窗口使用数组作为滑动窗口。每向右移动一次,就判断该字符串是否存在于窗口中。如果不存在,则继续向右移动,记录当前窗口长度;如果存在,则将左边距设置到窗口中字符的右侧。classSolution{/***@paramString$s*@returnInteger*/functionlengthOfLongestSubstring($s){$len=strlen($s);$左=$右=0;$ans=0;$队列=[];while($right<$len){//判断是否在$index=array_search($s[$right],$queue);$queue[]=$s[$right];if(false!==$index){$queue=array_slice($queue,$index+1);}$ans=max($ans,count($queue));$对++;}返回$ans;}}3.滑动窗口2与方案2相比,这里其实并没有使用数组,而是通过hash记录左右边界。每次right向右移动,判断字符串哈希表中对应的值(str索引)是否在left的右边。如果在右边,则left=max(index+1,left),如果不存在,则继续向右移动,记录当前窗口长度;如果存在,则将左边界设置为窗口中字符的右侧。复杂度分析时间复杂度:O(n),其中n为字符长度。我们要遍历字符的所有位置,处理每个位置,包括哈希查找,只需要O(1)的时间。空间复杂度:O(n),最大哈希长度。下面是PHP语言实现~~~~classSolution{/***@paramString$s*@returnInteger*/functionlengthOfLongestSubstring($s){$len=strlen($s);$左=$右=0;$散列=[];$ans=0;while($right<$len){//首先判断是否存在if(isset($hash[$s[$right]])){$left=max($hash[$s[$right]]+1,$左);}$hash[$s[$right]]=$right;$ans=max($ans,$right-$left+1);$对++;}返回$ans;}}