Longest Substring Without Repeating Characters

来源:互联网 发布:上海九院 双眼皮 知乎 编辑:程序博客网 时间:2024/05/24 23:11

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.

PHP实现代码如下

方法一

function maxSubString($str) {    $pre = -1;    $max = 0;    $tmp = [];    $len = strlen($str);    for ($i = 0; $i < $len; $i++) {        $tmp[$str[$i]] = -1;    }    for ($j = 0; $j < $len; $j++) {        $pre = max($pre, $tmp[$str[$j]]);        $max = max($max, $j - $pre);        $tmp[$str[$j]] = $j;    }    return $max;}$str = 'abcabcbb';//$str = 'bbbb';//$str = 'pwwkew';echo maxSubString($str);

方法二

function maxSubString2($str) {    $len = strlen($str);    $max_len = 0;    $cur_len = 0;    $i = 0;    $j = 0;    $tmp = [];    for ($k = 0; $k < $len; $k++) {        $tmp[$str[$k]] = 0;    }    while ($j < $len) {        if (isset($tmp[$str[$j]]) && $tmp[$str[$j]] == 0) {            $tmp[$str[$j]] = 1; // 遍历过置为1            $j++;        } else {            while ($str[$i] != $str[$j]) {                $tmp[$str[$i]] = 0; //新候选字串从第一个重复字符(当s[i] == s[j]时候的i)的后一位开始算,之前的i不算,等效于没有被扫描到,所以设为false.                $i++;            }            $i++;            $j++;        }        $cur_len = $j - $i;          $max_len = $max_len > $cur_len ? $max_len : $cur_len;      }    return $max_len;}$str = 'abcabcbb';//$str = 'bbbb';//$str = 'pwwkew';echo maxSubString2($str);

另附上求该最长字符串的代码

function LNRS($str) {    $len = strlen($str);    $hash = [];    for ($i = 0; $i < $len; $i++) {        $hash[$str[$i]] = -1;    }    $dp = 0; //初始未重复字符串长度    $last_start = 0;    $maxlen = 0;    $end = 0;    for ($j = 0; $j < $len; $j++) {        if ($hash[$str[$j]] == -1) { // 未出现重复字符则dp累加            $dp++;        } else {            if ($last_start <= $hash[$str[$j]]) {                //当前字符出现在以$str[$j-1]为结尾的最长不重复子串中                $dp = $j - $hash[$str[$j]];                $last_start = $hash[$str[$j]] + 1;            } else {                //当前字符出现了,但不在以$str[$j-1]为结尾的最长不重复子串中,可以和第一种情况合并                $dp++;            }        }        $hash[$str[$j]] = $j; // 记录当前字符最后出现的下标          if($maxlen < $dp) {  // 记录最大不重复子串,以及最后出现的位置             $maxlen = $dp;              $end = $j;         }      }    echo "longest nonrepeat substr is " . substr($str, $end - $maxlen + 1, $maxlen);      return $maxlen; }//$str = 'abcabcbb';//$str = 'bbbb';$str = 'pwpwkew';echo LNRS($str);
阅读全文
0 0
原创粉丝点击