Posts Tagged 【dp】Longest Substring Without Repeating Characters

Longest Substring Without Repeating Characters

  Total Accepted: 59913  Total Submissions: 284544 My Submissions

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.

/*
我现在能想到的就是dp了
dp[i]表示包含i索引位置的字符在内的Longest Substring Without Repeating Characters 
dp[i] = {dp[i-1]+1,i处字符未重复} OR {,i处字符在dp[i-1]之内有重复}
未重复,s.charAt(i)先前出现的位置不在(i-mark[s.charAt(i)],i-1)内
*/
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s == null || s.isEmpty()) return 0;
        int len = s.length();
        if(len == 1) return 1;
        int[] mark = new int[256];
        int[] dp = new int[len];
        Arrays.fill(mark,-1);
        int max = 1;
        dp[0] = 1;
        mark[s.charAt(0)] = 0;
        for(int i = 1;i<len;i++) {
            if((mark[s.charAt(i)] + dp[i-1]) < i) {
                dp[i] = dp[i-1] +1;
            } else {
                dp[i] = i - mark[s.charAt(i)];
            }
            mark[s.charAt(i)] = i;
            max = Math.max(max,dp[i]);
        }
        return max;
    }
}
/*
google了一下
好像自己前面搞的有点复杂,但是思路还是dp的那个
以i为索引的字符结尾的最大非重复子字符串数目,end-start+1
因为没有必要记住所有的dp[i],总是在Math.max中,记住前一个dp[i-1]就可以
所以开辟两个就行start和end,节省空间
*/
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s == null || s.isEmpty()) return 0;
        int len = s.length();
        if(len == 1) return 1;
        int[] mark = new int[256];
        int max = 1;
        int start = 0,end = 1;
        Arrays.fill(mark,-1);
        mark[s.charAt(0)] = 0;
        while(end < len) {
            int i = mark[s.charAt(end)];
            if(i >= start) start = i+1;
            mark[s.charAt(end)] = end;
            max = Math.max(max,end - start +1);
            end++;
        }
        return max;
    }
}




Have you met this question in a real interview? 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值