|
| 1 | +/** |
| 2 | + * [28] 找出字符串中第一个匹配项的下标 |
| 3 | + * |
| 4 | + * 给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。 |
| 5 | + * |
| 6 | + * <strong class="example">示例 1: |
| 7 | + * |
| 8 | + * 输入:haystack = "sadbutsad", needle = "sad" |
| 9 | + * 输出:0 |
| 10 | + * 解释:"sad" 在下标 0 和 6 处匹配。 |
| 11 | + * 第一个匹配项的下标是 0 ,所以返回 0 。 |
| 12 | + * |
| 13 | + * <strong class="example">示例 2: |
| 14 | + * |
| 15 | + * 输入:haystack = "leetcode", needle = "leeto" |
| 16 | + * 输出:-1 |
| 17 | + * 解释:"leeto" 没有在 "leetcode" 中出现,所以返回 -1 。 |
| 18 | + * |
| 19 | + * |
| 20 | + * 提示: |
| 21 | + * |
| 22 | + * 1 <= haystack.length, needle.length <= 10^4 |
| 23 | + * haystack 和 needle 仅由小写英文字符组成 |
| 24 | + * |
| 25 | + */ |
| 26 | +pub struct Solution {} |
| 27 | + |
| 28 | +// problem: https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/ |
| 29 | +// discuss: https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/discuss/?currentPage=1&orderBy=most_votes&query= |
| 30 | + |
| 31 | +// submission codes start here |
| 32 | + |
| 33 | +impl Solution { |
| 34 | + pub fn str_str(haystack: String, needle: String) -> i32 { |
| 35 | + if needle.len() > haystack.len() { |
| 36 | + return -1 |
| 37 | + } |
| 38 | + let a = haystack.as_bytes(); |
| 39 | + let b = needle.as_bytes(); |
| 40 | + 'outer: for i in 0..(haystack.len() - needle.len() + 1) { |
| 41 | + for j in (0..needle.len()) { |
| 42 | + if a[i + j] != b[j] { |
| 43 | + continue 'outer; |
| 44 | + } |
| 45 | + } |
| 46 | + return i as i32 |
| 47 | + } |
| 48 | + -1 |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +// submission codes end |
| 53 | + |
| 54 | +#[cfg(test)] |
| 55 | +mod tests { |
| 56 | + use super::*; |
| 57 | + |
| 58 | + #[test] |
| 59 | + fn test_28() { |
| 60 | + assert_eq!(Solution::str_str("haystack".to_string(), "haystack".to_string()), 0); |
| 61 | + assert_eq!(Solution::str_str("haystack".to_string(), "needle".to_string()), -1); |
| 62 | + } |
| 63 | +} |
0 commit comments