当前位置: 面试刷题>> 字符串置换 (经典算法题500道)


完整题目描述

字符串置换

给定两个字符串 s1s2,其中 s2 包含了一些由 {} 包围的占位符,如 "{0}""{1}" 等,这些占位符在字符串中按升序编号(即 {0}{1}{2}...)。你需要编写一个函数,该函数接受这两个字符串作为输入,并返回一个字符串,其中 s2 中的每个占位符都被 s1 中对应位置的字符串片段所替换。如果 s1 中的字符串片段不足以替换所有占位符,则忽略多余的占位符;如果 s1 中的字符串片段多于占位符,则忽略多余的字符串片段。

示例

  • 输入:s1 = "hello", s2 = "world {0}"

  • 输出:"world hello"

  • 输入:s1 = "apple banana cherry", s2 = "I have {0}, {1} and {2}"

  • 输出:"I have apple, banana and cherry"

  • 输入:s1 = "xyz", s2 = "this is a test {0} {2} {1}"

  • 输出:"this is a test xyz {2} x"(注意 {2} 未被替换,因为 s1 中没有足够的片段)

PHP 示例代码

function stringReplace($s1, $s2) {
    $parts = preg_split('/\{(\d+)\}/', $s2, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
    $result = '';
    $s1Parts = explode(' ', $s1); // 假设s1由空格分隔
    $index = 0;

    foreach ($parts as $part) {
        if (is_numeric($part)) {
            $index = intval($part);
            if (isset($s1Parts[$index])) {
                $result .= $s1Parts[$index];
            }
        } else {
            $result .= $part;
        }
    }

    return $result;
}

// 示例调用
echo stringReplace("hello", "world {0}"); // 输出 "world hello"
echo PHP_EOL;
echo stringReplace("apple banana cherry", "I have {0}, {1} and {2}"); // 输出 "I have apple, banana and cherry"
echo PHP_EOL;
echo stringReplace("xyz", "this is a test {0} {2} {1}"); // 输出 "this is a test xyz {2} x"

注意:此PHP示例假设s1由空格分隔,且占位符编号从0开始。对于更复杂的字符串分割,可能需要更复杂的处理。

Python 示例代码

def string_replace(s1, s2):
    s1_parts = s1.split()  # 假设s1由空格分隔
    result = []
    i = 0
    last_end = 0

    for match in re.finditer(r'\{(\d+)\}', s2):
        result.append(s2[last_end:match.start()])
        index = int(match.group(1))
        if index < len(s1_parts):
            result.append(s1_parts[index])
        last_end = match.end()

    result.append(s2[last_end:])
    return ''.join(result)

import re

# 示例调用
print(string_replace("hello", "world {0}"))  # 输出 "world hello"
print(string_replace("apple banana cherry", "I have {0}, {1} and {2}"))  # 输出 "I have apple, banana and cherry"
print(string_replace("xyz", "this is a test {0} {2} {1}"))  # 输出 "this is a test xyz {2} x"

JavaScript 示例代码

function stringReplace(s1, s2) {
    const s1Parts = s1.split(/\s+/); // 使用正则匹配一个或多个空格来分割s1
    let result = '';
    let lastIndex = 0;
    let match;
    const regex = /\{(\d+)\}/g;

    while ((match = regex.exec(s2)) !== null) {
        result += s2.substring(lastIndex, match.index);
        const index = parseInt(match[1]);
        if (index < s1Parts.length) {
            result += s1Parts[index];
        }
        lastIndex = regex.lastIndex;
    }

    result += s2.substring(lastIndex);
    return result;
}

// 示例调用
console.log(stringReplace("hello", "world {0}")); // 输出 "world hello"
console.log(stringReplace("apple banana cherry", "I have {0}, {1} and {2}")); // 输出 "I have apple, banana and cherry"
console.log(stringReplace("xyz", "this is a test {0} {2} {1}")); // 输出 "this is a test xyz {2} x"

这些示例代码均实现了字符串置换的功能,并考虑了输入字符串的多种情况。在码小课网站上,你可以找到更多关于字符串处理和正则表达式等内容的分享,以帮助你深入学习相关知识。

推荐面试题