Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
Subscribe to see which companies asked this question
<?php /** * Created by PhpStorm. * User: polestar * Date: 16/11/15 * Time: 下午6:19 * */ function lengthOfLongestSubstring($string){ $sArr = str_split($string); $countDict = array(); $ans = $start = $end = 0; foreach($sArr as $i){ $end += 1; $countDict[$i] = isset($countDict[$i])? $countDict[$i]+1 : 1; while ($countDict[$i] > 1) { $countDict[$string[$start]] -= 1; $start += 1; } $ans = max($ans,$end - $start); } return $ans; } $str = 'abctbtyuefg'; echo lengthOfLongestSubstring($str);