当前位置: 面试刷题>> 移除子串 (经典算法题500道)


完整题目描述

题目:移除子串

描述:给定一个字符串s和一个子串t,请编写一个函数,从字符串s中移除所有出现的子串t,并返回移除后的结果字符串。注意,移除时需要考虑子串ts中的重叠情况。

示例

  • 输入:s = "helloworld", t = "ll"
  • 输出:"heoword"

说明:在这个例子中,s中包含两个t("ll"),移除这两个子串后得到"heoword"

示例代码

PHP

function removeSubstring($s, $t) {
    $len_s = strlen($s);
    $len_t = strlen($t);
    $result = '';
    $i = 0;

    while ($i < $len_s) {
        if (substr($s, $i, $len_t) == $t) {
            $i += $len_t; // 跳过当前子串
        } else {
            $result .= $s[$i]; // 否则,将字符添加到结果字符串
            $i++;
        }
    }

    return $result;
}

// 示例
$s = "helloworld";
$t = "ll";
echo removeSubstring($s, $t); // 输出: heoword

Python

def removeSubstring(s, t):
    i = 0
    result = []
    while i < len(s):
        if s[i:i+len(t)] == t:
            i += len(t)
        else:
            result.append(s[i])
            i += 1
    return ''.join(result)

# 示例
s = "helloworld"
t = "ll"
print(removeSubstring(s, t))  # 输出: heoword

JavaScript

function removeSubstring(s, t) {
    let result = '';
    let i = 0;

    while (i < s.length) {
        if (s.substr(i, t.length) === t) {
            i += t.length; // 跳过当前子串
        } else {
            result += s[i]; // 否则,将字符添加到结果字符串
            i++;
        }
    }

    return result;
}

// 示例
let s = "helloworld";
let t = "ll";
console.log(removeSubstring(s, t)); // 输出: heoword

码小课网站中有更多相关内容分享给大家学习,希望这些示例能帮助你更好地理解题目并编写出相应的算法。

推荐面试题