leetcode 2019.3.20

question 3

描述

given a string, find the length of the longest substring without repeating characters

思路

1、贪心算法
2、用c++实现,使用unordered_map 建立一个字符和数字的映射,遍历字符串,如果字符不重复,存入map,如果重复,则修改map中已有字符对应的数字,修改当前最长字符串长度

实现
int lengthOfLongestSubstring(string s){
    int res=0,left=-1;
    unordered_map <int ,int > m;
    for(int i=0;i<s.size();i++){
        if(m.count(s[i])&&m[s[i]]>left){
            left=m[s[i]];
        }
        m[s[i]]=i;
        res=max(res,i-left);
    }
    return res;

分析

复杂度 O(n^2)

核心

unordered_map

Question 55 jump game

描述

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

思路
1、动态规划

维护一个一维数组dp[i],表示到达当前位置的剩余步数
状态转移:dp[i]=max(dp[i-1],num[i-1)-1
*要么从上一个直接跳过来,要么从上一格的最佳解跳过来
if dp[i]<0 无解

bool canJump(vector<int>& nums) {
    //construct a vector of size(num.size()), each element is initialized with value 0
    vector<int> dp(nums.size(),0);
    for(int i=1;i<nums.size();i++){
        dp[i]=max(dp[i-1],nums[i-1])-1;
        if(dp[i]<0){
            return false;
        }
    }
    return true;
}
2、贪心算法

只关心能到达的最远位置,维护一个 int 类型的 reach

bool canJump2(vector<int> & nums){
    int reach=0;
    for(int i=0;i<nums.size();i++){
        if(i>reach || reach>=nums.size()-1){
            break;
        }
        reach=max(reach,nums[i]+i);
    }
    return (reach>=nums.size()-1);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值