LeetCode-3. Longest Substring Without Repeating Characters

3.

Longest Substring Without Repeating Characters

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.


public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int length=0;
        for(int i=0;i<s.length();i++){
            for(int j=1;j<s.length()+1;j++){
                if(i>=j){
                    continue;
                }
                if(noRepeatChar(s.substring(i,j))){
                    if(j-i>length){
                        length=j-i;
                    }
                }
            }
        }
        return length;
    }

    private boolean noRepeatChar(String str){
        char[] charArr=str.toCharArray();
        int [] arr=new int[26];
        for(char c:charArr){
            arr[c-97]++;
        }
        for(int i:arr){
            if(i>1){
                return false;
            }
        }
        return true;
    }
}

这个解时间复杂度是o(N^3)的样子,TLE是必然的了。这个解假定了输入的字符串只包括a-z,但是也982 / 983 test cases passed了,最后一个test case包括了各种乱七八糟的char,所以有时候会TLE,有时候会数组越界。
慢慢想吧。啊。


这道题花了我两个小时,damn it

public class Solution {
    public int lengthOfLongestSubstring(String s) {

        HashMap<Character,Integer> map=new HashMap<Character,Integer>();
        int max=0;
        for(int left=0,right=0;right<s.length();right++){
            char c=s.charAt(right);
            if(map.containsKey(c)){
                int target=map.get(c)+1;
                for(int l=left;l<target;l++){
                    map.remove(s.charAt(l));
                }

                left=target;

            }

            map.put(s.charAt(right),right);
            max=Math.max(max,right-left+1);

        }

        return max;
    }
}

主要的思路就是用一个map,key存出现过的char,value为他的位置。
然后遍历字符串,如果出现了相同的,就把左指针移到之前出现过相同的char的位置的右一位,然后继续往后找。
啊,语言真的不好形容,还是看代码吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值