LeetCode——Longest Substring Without Repeating Characters

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.

问题描述:

给定一个字符串,寻找最长无重复子串,返回最长长度。

解决方案:

1、暴力搜索,O(n^2)不考虑。

2、举个例子,abcdecf

说明:使用两个游标,i、j 初始为0,len为字符串长度,maxLen为要返回的无重复最长子串的长度,exist数组为标识元素是否重复,默认支持ASCII,数组大小开到256.

a)对于字符串 a b c d e c f 来说:i 增长到第二个'c'的下标[5],发现之前'c'出现过;

b)这时,首先更新最大长度;

c)然后while循环执行 j++ 自增到第一个'c',同时将第一个'c'之前的元素的存在标志清除。

d)i++,j++,从a b c d e f 处继续向后执行

e)最后在return之前,再更新maxLen

 1 public int lengthOfLongestSubstring(String s) {
 2         int len = s.length();
 3         boolean[] exist = new boolean[256];
 4         for (int i = 0; i < 256; i++) {
 5             exist[i] = false;
 6         }
 7         int i = 0, j = 0;
 8         int maxLen = 0;
 9         while (i < len) {
10             if (!exist[s.charAt(i)]) {//如果访问的元素没有出现过
11                 exist[s.charAt(i)] = true;
12                 i++;
13             } else {//发现两个一样的,现在i指向两个元素中的第二个
14 
15                 maxLen = Math.max(i - j, maxLen);//更新最大长度
16                 while (s.charAt(i) != s.charAt(j)) {
17                     exist[s.charAt(j)] = false;//重置exist数组
18                     j++;
19                 }//while循环结束后,现在i、j都是指向那个重复元素,j指向第一个
20                 i++;
21                 j++;
22             }
23         }
24         maxLen = Math.max(maxLen, len - j);//最后再更新最大程度
25         //System.out.println(maxLen);
26         return maxLen;
27     }

重新做了一遍,发现还没第一次做的好:

public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        HashMap<Character, Integer> exist = new HashMap<>();
        int len = 0, res = 0, last_j = 0;
        for (int i = 0; i < s.length(); i++) {
            if (exist.get(s.charAt(i)) == null) {
                exist.put(s.charAt(i), i);
                len++;
            } else {
                int j = exist.get(s.charAt(i));
                len = i - j;
                for (int k = last_j; k <= j; k++) {
                    exist.remove(s.charAt(k));
                }
                exist.put(s.charAt(i), i);
                last_j = j + 1;
            }
            res = Math.max(len, res);
        }
        System.out.println(res);
        return res;
    }

原创文章,转载请注明出处。

原文地址:https://www.cnblogs.com/aboutblank/p/3692555.html