[LeetCode] Longest Substring Without Repeating Characters

题目:

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.


思路:

暴力做法是找到s的每一个子串,再对子串进行重复字符检测,但是肯定不会通过LeetCode OJ的测试。基本思路还是循环,但是在遍历和判断是否有重复字符的时候,选择用空间换时间的策略,引入两个数组exist[]和position[],分别存储的信息是该字符是否出现在当前子串中以及出现的下标。需要注意的是字符集不仅仅是{a,b,c……,z},可能包括特殊字符,这里考虑的是ASCII字符集。


代码

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int start = 0,maxLen = 0;
        int[] position = new int[255];
        boolean[] exist = new boolean[255];
        
        if(s == null || s.equals(""))
            return 0;
        
        for(int i = 0;i < 255;i++){
            position[i] = -1;
            exist[i] = false;
        }
        
        for(int i = 0;i < s.length();i++){
            if(!exist[s.charAt(i) - ' ']){
                position[s.charAt(i) - ' '] = i;
                exist[s.charAt(i) - ' '] = true;
                maxLen = ((i - start) + 1 > maxLen) ? (i - start) + 1 : maxLen;
            }
            else{
                for(int j = start;j < i;j++){
                    exist[s.charAt(j) - ' '] = false;
                }
               
                start = position[s.charAt(i) - ' '] + 1;
                exist[s.charAt(start) - ' '] = true;
                position[s.charAt(start) - ' '] = start;
                i = start;
           }
        }
        return maxLen;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值