LeetCode-Longest Substring Without Repeating Characters

28 篇文章 0 订阅
22 篇文章 0 订阅

This question belong to the same category as those such as "longest substring without repeating characters", "minimum window substring", and "substring with concatenation of all words". To solve this kind of question we can use two pointers and a hash table. When the key of the hash table is char, we can simply use an array as the hash table. The most important idea in solving this kind of questions is "how to update the "start" pointer" and the solution to these questions seem usually differ only in this respect.

这段话写的很好, 都是用hash 有的题用map(longest substring at most 2 distinct char)有的题用hashset就可以(这个题)然后记录一个start指针

检查新碰到的这个char之前遇到过没有,假如遇到过就将start移动到这个char第一次出现过的地方的后面 就是重新开始一个substring。

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if ( s == null || s.length() == 0 )
            return 0;
        HashSet<Character>set = new HashSet<Character>();
        int len = 0;
        int start = 0;
        int longest = 0;
        for ( int i = 0; i < s.length(); i ++ ){
            if ( !set.contains(s.charAt(i))) {
                set.add(s.charAt(i));
                len ++;
            }
            else{
                while ( s.charAt(start) != s.charAt(i)){
                    set.remove(s.charAt(start));
                    start ++;
                }
                start ++;
                len = i - start +1;
            }
            if ( len > longest)
                longest = len;
        }
        return longest;
    }
}

下面这个人写的更简洁一点 用了hashmap value存这个char出现过的所有位置 省去了我一个一个移动start的这步,直接移动到max(这个key随影的values)就是上一次出现的地方

   public int lengthOfLongestSubstring(String s) {
        if (s.length()==0) return 0;
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int max=0;
        for (int i=0, j=0; i<s.length(); ++i){
            if (map.containsKey(s.charAt(i))){
                j = Math.max(j,map.get(s.charAt(i))+1);
            }
            map.put(s.charAt(i),i);
            max = Math.max(max,i-j+1);
        }
        return max;
    }
才意识到 这就是dp了 晕



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值