3. Longest Substring Without Repeating Characters

Question Description

Screen Shot 2016-10-07 at 20.00.12.png

My Code

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s.length() < 1) return 0;
        int[] calculate = new int[s.length()];
        Arrays.fill(calculate, -1);
        for (int i = 0; i < s.length(); i++) {
            dp(s, calculate, i);
        }
        int result = 0;
        for (int i: calculate
                ) {
            if (i > result) result = i;
        }
        return result;
    }
    
    private int dp(String s, int[] calculate, int i) {
        if (i == 0) {
            calculate[i] = 1;
            return 1;
        }
        if (calculate[i] != -1) return calculate[i];
        String sub = s.substring(i - dp(s, calculate, i - 1), i);
        String thisChar = String.valueOf(s.charAt(i));
        calculate[i] = sub.contains(thisChar) ? sub.length() - sub.indexOf(thisChar) : calculate[i - 1] + 1;
        return calculate[i];
    }
}

Test Result

Screen Shot 2016-10-07 at 19.59.42.png

Solution

Dynamic programming. Use int[] calculate to record the max length of String ended index i. The value of calculate[i] relies on calculate[i - 1]. If max-length String that ends with index i - 1 doesn't contain char at i, calculate[i] = 1 + calculate[i - 1]. Else, calculate[i] = 1 + (length of String begins after char at i in max-length String that ends with index i - 1).

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容