leetcode第三题:求给定字符串中最长无重复子串的长度

来源:互联网 发布:图像尺寸测量软件 编辑:程序博客网 时间:2024/05/18 00:22

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);

0 0
原创粉丝点击