You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust生命周期不匹配错误求助:最长公共前缀函数实现问题

修复Rust最长公共前缀函数的生命周期错误

问题代码

我正在学习Rust字符串相关知识,想要实现一个计算字符串列表最长公共前缀的函数,代码如下:

impl Solution {
    pub fn get_common_prefix(s1: &String, s2: &String) -> String {
        let mut idx: usize = 0;
        if s1.len() > s2.len() {
            std::mem::swap(&mut s1, &mut s2);
        }
        
        while idx < s1.len() && s1.chars().nth(idx) == s2.chars().nth(idx) {
            idx += 1;    
        }
        return s1[0..idx].to_string();
        
        
    }
    pub fn longest_common_prefix(mut strs: Vec<String>) -> String {
        strs.sort();
        let mut longest_pref = strs[0];
        for i in 0..strs.len() {
            longest_pref = Self::get_common_prefix(&longest_pref, &strs[i]);
        }
        return longest_pref;
    }
}

错误信息

运行时出现生命周期不匹配错误:

Line 5, Char 37: lifetime mismatch (solution.rs)
  |
2 |     pub fn get_common_prefix(s1: &String, s2: &String) -> String {
  |                                  -------      ------- these two types are declared with different lifetimes...
...
5 |             std::mem::swap(&mut s1, &mut s2);
  |                                     ^^^^^^^ ...but data from `s2` flows into `s1` here

修复方案

错误原因

get_common_prefix中s1和s2是不同生命周期的引用,std::mem::swap尝试交换可变引用会打破Rust的生命周期约束,导致编译器报错。同时原代码中chars().nth(idx)的方式效率极低,每次调用都会从头遍历字符。

修复后的代码

impl Solution {
    pub fn get_common_prefix(s1: &str, s2: &str) -> String {
        // 绑定短、长字符串,避免交换引用
        let (short, long) = if s1.len() <= s2.len() {
            (s1, s2)
        } else {
            (s2, s1)
        };

        // 用迭代器配对遍历字符,收集公共前缀
        short.chars()
            .zip(long.chars())
            .take_while(|(c1, c2)| c1 == c2)
            .map(|(c, _)| c)
            .collect()
    }

    pub fn longest_common_prefix(mut strs: Vec<String>) -> String {
        if strs.is_empty() {
            return String::new();
        }
        // 排序后只需比较首尾元素,即可得到最长公共前缀
        strs.sort_unstable();
        let first = strs.first().unwrap();
        let last = strs.last().unwrap();
        Self::get_common_prefix(first, last)
    }
}

关键修改点

  • 避免引用交换:通过let (short, long)绑定短、长字符串,绕过直接交换引用的生命周期问题,同时保持逻辑不变。
  • 优化字符遍历:使用zip配对两个字符串的字符迭代器,take_while截取到第一个不匹配的位置,最后collect成字符串,效率远高于多次nth(idx)调用。
  • 简化主逻辑:字符串排序后,首尾元素的公共前缀就是整个列表的最长公共前缀,无需遍历所有元素,大幅减少不必要的计算。
  • 参数类型优化:将&String改为&str,让函数接受更通用的字符串引用,提升灵活性。

内容的提问来源于stack exchange,提问作者mascai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 04:22:40