美文网首页
rust leetcode Longest Substring

rust leetcode Longest Substring

作者: 奔跑的蛙牛 | 来源:发表于2019-11-18 21:10 被阅读0次

    每日小刷

    median-of-two-sorted-arrays

    Runtime Memory
    4ms 2.6m
    use std::cmp;
    use std::collections::HashMap;
    use std::collections::HashSet;
    impl Solution {
        pub fn all_unique(arr: &Vec<char>, i: usize, j: usize) -> bool {
            let mut hash_set: HashSet<char> = HashSet::new();
            for k in i..(j + 1) {
                if hash_set.contains(&arr[k]) {
                    return false;
                }
                hash_set.insert(arr[k]);
            }
            true
        }
    
        // 暴力法 O(n^3) O(n)
        pub fn length_of_longest_substring_violence(s: String) -> i32 {
            let text: Vec<char> = s.chars().collect();
            let mut max_number = 0;
            for i in 0..(s.len() - 1) {
                for j in i + 1..s.len() {
                    if Solution::all_unique(&text, i, j) {
                        max_number = cmp::max(j - i, max_number)
                    }
                }
            }
            (max_number + 1) as i32
        }
        pub fn length_of_longest_substring(s: String) -> i32 {
            let mut hashMap: HashMap<&char, usize> = HashMap::new();
            let text: Vec<char> = s.chars().collect();
            let mut max = 0;
            let mut last_index = 0;
            for c in 0..text.len() {
                if hashMap.contains_key(&text[c]) {
                    last_index = if hashMap.get(&text[c]).unwrap() + 1 > last_index {
                        hashMap.get(&text[c]).unwrap() + 1
                    } else {
                        last_index
                    };
                }
                max = cmp::max(c - last_index + 1, max);
                hashMap.insert(&text[c], c);
            }
            max as i32
        }
        // a b a c d  b 1 2
        a b c d
        0 0 0 0
        3 2 
    }
    

    好好学习rust和基础算法

    相关文章

      网友评论

          本文标题:rust leetcode Longest Substring

          本文链接:https://www.haomeiwen.com/subject/iyqiictx.html