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;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值