LeetCode 3. Longest Substring Without Repeating Characters(java)

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.
解题思路:首先我们假设走到i-1的位置时的最大subarray时的(start ~ i-1)中的start已经被维护,那么到了第i个位置,我们需要判断,第i个字符是否是重复字符,如果是,那么start移到start后面第一个相同字符的后面一个;如果不是,那么加进hashset,然后update那个max,最后走完返回max即可。
class Solution {
    public int lengthOfLongestSubstring(String s) {
        //special case
        if (s.length() <= 1) return s.length();
        //base case
        HashSet<Character> set = new HashSet<>();
        int start = 0, max = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (set.contains(c)) {
                for (int j = start; j < i; j++) {
                    char cc = s.charAt(j);
                    if ( cc== c) {
                        start = j + 1;
                        break;
                    } else {
                        set.remove(cc);
                    }
                }
            } else {
                set.add(c);
                if (i - start + 1 > max) {
                    max = i - start + 1;
                }
            }
        }
        return max;
    }
}
看到以Character为key的hashmap就无脑用数组!!!因为Character的范围是固定的,所以可以直接用数组来代替。以下代码的效率更高。
 public int lengthOfLongestSubstring(String s) {
        //special case
        if (s.length() <= 1) return s.length();
        //base case
        int[] index = new int[256];
        int max = 0, start = 0;
        //由于0在这里可以是index = 0的意思,因此这里我们用-1来初始化index.
        for (int i = 0; i < 256; i++) {
            index[i] = -1;
        }
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (index[c] == -1) {
                index[c] = i;
                max = Math.max(max, i - start + 1);
            } else {
                for (int j = start; j < index[c]; j++) {
                    index[s.charAt(j)] = -1;
                }
                start = index[c] + 1;
                index[c] = i;
            }
        }
        return max;
    }
阅读更多
文章标签: string java
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

LeetCode 3. Longest Substring Without Repeating Characters(java)

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭