Longest Substring Without Repeating Characters

本文介绍了两种寻找字符串中最长无重复字符子串的方法,并提供PHP实现代码。通过实例演示了如何找出并返回最长无重复子串的长度。

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值