leetcode简单题9 N.28 找出字符串中第一个匹配元素的下标 rust描述

 

// "sadbutsad" "sad" 0
// "leetcode" "leeto" -1
// "你好吗" "好" 3 额外加的
// 内置的 str::find 函数
pub fn str_str(haystack: String, needle: String) -> i32 {
    if needle.is_empty() {// 空串匹配任意字符串 虽然题目说不会有空字符串
        return 0;
    }
    if let Some(pos) = haystack.find(&needle) {// 查找第一个匹配项 汉字占三个字节
        pos as i32
    } else {
        -1
    }
}
// kmp 算法 辅助函数用于计算next数组
pub fn str_str2(haystack: String, needle: String) -> i32 {
    let m = needle.len();
    let n = haystack.len();
    if m == 0 {
        return 0;
    }
    let mut lps = vec![0; m];
    let mut j = 0; // needle index

    // Preprocess the pattern (calculate lps array)
    compute_lps(&needle.as_bytes(), m, &mut lps);//关联函数调用要self

    let haystack_bytes = haystack.as_bytes();
    let needle_bytes = needle.as_bytes();
    let mut i = 0; // haystack index
    while i < n {
        if needle_bytes[j] == haystack_bytes[i] {
            j += 1;
            i += 1;
        }
        else if i < n && needle_bytes[j] != haystack_bytes[i] {
            if j != 0 {
                j = lps[j - 1];
            } else {
                i += 1;
            }
        }
        if j == m {
            return (i - j) as i32;
        }
    }
    -1
}

fn compute_lps(pattern: &[u8], m: usize, lps: &mut Vec<usize>) {
    let mut len = 0;
    let mut i = 1;
    lps[0] = 0; // lps[0] is always 0

    while i < m {
        if pattern[i] == pattern[len] {
            len += 1;
            lps[i] = len;
            i += 1;
        } else {
            if len != 0 {
                len = lps[len - 1];
            } else {
                lps[i] = 0;
                i += 1;
            }
        }
    }
}



fn main() {
    assert_eq!(str_str("sadbutsad".to_string(), "sad".to_string()), 0);
    assert_eq!(str_str("leetcode".to_string(), "leeto".to_string()), -1);
    assert_eq!(str_str("你好吗".to_string(), "好".to_string()), 3);


    assert_eq!(str_str2("sadbutsad".to_string(), "sad".to_string()), 0);
    assert_eq!(str_str2("leetcode".to_string(), "leeto".to_string()), -1);
    assert_eq!(str_str2("你好吗".to_string(), "好".to_string()), 3);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值