leetcodeLongest Substring Without Repeating Characters

18 篇文章 0 订阅
6 篇文章 0 订阅

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

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring"pwke" is a subsequence and not a substring.

 


网上广为流传的fa方法是用hashmap存储数据,虽然我第一感觉就是动态规划,大门时在空间和时间fu'z复杂度上面还是相差许多,所以接下来就要把这几行精简代码思想具体化

int lengthOfLongestSubstring(string s) {
        vector<int> dict(256, -1);
        int maxLen = 0, start = -1;
        for (int i = 0; i != s.length(); i++) {
            if (dict[s[i]] > start)
                start = dict[s[i]];
            dict[s[i]] = i;
            maxLen = max(maxLen, i - start);
        }
        return maxLen;
  

首先最好用现成的hashmap

 HashMap<Character, Integer> map = new HashMap<Character, Integer>();

感觉酷酷的,至于256,还不清楚, dict下标代表各种字符,而value是字符串的下标

思路是这样

从头kai'开始便利字符串,遇到字母,就把它的下标放进hashmap中,当我们遇到第一个重复的字符,由于这个字符是char c=s[i]在hashmap中对应的value不为-1,这个时候就找到了第一个重复位置,然后ba把这个重复位置记录下来并更新,如果以后遇到其他字符重复时候,那么长度就要从start和重复字符b位置中最大计算了,总之就是把重复位置找到,并更新。理解起来还是有点难度,hashmap用起来就很顺手了,

当我们遇到cho重复字符时,那么长度就要从shan上一个重复字符开始。这个感觉没有我的dp好用,理解起来有点费劲。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值