前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >rust leetcode Longest Substring Without Repeating Characters #3

rust leetcode Longest Substring Without Repeating Characters #3

作者头像
用户2436820
发布2019-11-21 15:01:54
4060
发布2019-11-21 15:01:54
举报

每日小刷

median-of-two-sorted-arrays

Runtime

Memory

4ms

2.6m

代码语言:javascript
复制
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工程师

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 每日小刷
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档