Longest Substring Without Repeating Characters 最长不重复子串 @LeetCode

Ref: http://fisherlei.blogspot.com/2012/12/leetcode-longest-substring-without.html

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

[解题思路]
从左往右扫描,当遇到重复字母时,以上一个重复字母的index +1,作为新的搜索起始位置。这时需要清空Map,并且从index+1开始重新进行搜索。

比如


直到扫描到最后一个字母。

代码用Java 重写如下:

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        
        //http://fisherlei.blogspot.com/2012/12/leetcode-longest-substring-without.html
        // 使用hashmap 来记录各个字符最后出现的位置,如果之前出现过,则需要将窗口在前面截断,否则当前长度
        // 应该在上一个长度加1;
        
        int len = s.length();
        int max = 0;
        int last = 0;
        
        HashMap
   
   
    
     h = new HashMap
    
    
     
     ();
        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            if (h.containsKey(c)) {
                // go back the the last index and count again.
                i = h.get(c);
                h.clear();
                last = 0;
                continue;
            } else {
                last++;
            }
            h.put(s.charAt(i), i);
            max = Math.max(max, last);
        }
        
        return max;
    }
}

    
    
   
   

Solution 2:
优化后,使用一个start来记录起始的index,判断在hash时 顺便判断一下那个重复的字母是不是在index之后。这样可以避免hash的clear和重建操作,也不需要退回前面去重新计算和加入map。

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        
        //http://fisherlei.blogspot.com/2012/12/leetcode-longest-substring-without.html
        // 使用hashmap 来记录各个字符最后出现的位置,如果之前出现过,则需要将窗口在前面截断,否则当前长度
        // 应该在上一个长度加1;
        
        int len = s.length();
        int max = 0;
        int last = 0;
        int start = 0;
        
        HashMap
   
   
    
     h = new HashMap
    
    
     
     ();
        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            if (h.containsKey(c) && h.get(c) >= start) {
                // go back the the last index and count again.
                start = h.get(c) + 1;
                last = i - start;
            } 
                
            last++;
            h.put(s.charAt(i), i);
            max = Math.max(max, last);
        }
        
        return max;
    }
}

    
    
   
   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值