esc to dismiss
x

信息

题解

Warning

输入indices不保证有序, 因此需要整体组合后排序, 否则会产生互相影响.

pub fn find_replace_string(
    s: String,
    indices: Vec<i32>,
    sources: Vec<String>,
    targets: Vec<String>,
) -> String {
    let mut ops = vec![];
    for i in 0..indices.len() {
        ops.push((
            indices[i] as usize,
            sources[i].as_str(),
            targets[i].as_str(),
        ));
    }
    ops.sort_by(|a, b| a.0.cmp(&b.0));

    let mut ans = String::new();

    let mut cursor = 0;
    for (start, source, target) in ops {
        if start > cursor { 
            // 如果中间存在不需要替换的, 跳过的, 需要补齐
            ans.push_str(s.get(cursor..start).unwrap());
            cursor = start; // 游标向前, cursor 始终是 s 种的需要判定的起始(字符)
        }
        if s.get(start..).unwrap().starts_with(source) {
            ans.push_str(target);
            cursor += source.len(); // cursor是相对s的, 注意替换的长度
        }
    }
    if cursor < s.len() {
        ans.push_str(s.get(cursor..).unwrap());
    }
    ans
}
x