LeetCode 3. Longest Substring Without Repeating Characters

Posted 来一点音乐

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 3. Longest Substring Without Repeating Characters相关的知识,希望对你有一定的参考价值。

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.

思路:1.将每组子串的字母存在hashset中,判断当前字母是否存在set中(hash查找效率高)。

2.若存在则判断下一组子串。下组子串的初始位置在重复字母处位置+1。

3.若不存在则将此字母存在容器中,并判断当然容器大小是不是最大, 若是最大表示当前长度最大。

如abcabcbb,

1.容器中一次存入第一个子串abc,到第2个a事与第一个a重复,容器中移除第一个a到第一个子串的初始位置0的所有元素,容器中的元素为abc。

2.容器中子串bca,第二个b重复,相同办法。

注:判断下个子串的初始位置,为重复字母的位置+1,类似于kmp算法。

 1 public int lengthOfLongestSubstring(String s) {
 2         int max = 0;
 3         int flag = 0;
 4         Set<Character> set = new HashSet<Character>();
 5         char[] a = s.toCharArray();
 6         for(int i=0;i<a.length;i++) {
 7             if(!set.contains(a[i])) {
 8                 set.add(a[i]);
 9                 if(max<set.size()) {
10                     max = set.size();
11                 }
12             }else {
13                 int j = flag;
14                 while(a[i]!=a[j]) {
15                     set.remove(a[j]);
16                     j++;
17                 }
18                 flag = j+1;
19             }
20             //System.out.println(set.toString());
21         }
22         return max;
23         
24     }

 

以上是关于LeetCode 3. Longest Substring Without Repeating Characters的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 3. Longest Substring Without Repeating Characters

LeetCode 3. Longest Substring Without Repeating

3. 没有重复字母的最长子串 [leetcode 3: Longest Substring Without Repeating Characters]

3. 没有重复字母的最长子串 [leetcode 3: Longest Substring Without Repeating Characters]

leetcode longest consecutive sequence

leetcode 3. Longest Substring Without Repeating Characters (Python版)