###### 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 {
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;
}

#### [LeetCode] 003. Longest Substring Without Repeating Characters (Medium) (C++/Java/Python)

2015-02-27 12:55:12

#### leetcode:3. Longest Substring Without Repeating Characters (java)

2016-06-20 20:36:28

#### LeetCode(3) Longest Substring Without Repeating Characters

2013-11-23 04:25:39

#### 字符串+哈希表+小动态规划（Longest Substring Without Repeating Characters -- LeetCode）

2016-09-03 12:16:17

#### Longest Substring Without Repeating Characters -- LeetCode

2014-02-26 01:53:37

#### LeetCode 3.Longest Substring Without Repeating Characters c语言版

2017-07-15 17:35:47

#### leetcode 3 Longest Substring Without Repeating Characters最长无重复子串

2016-04-05 22:27:27

#### leetcode 3 : Longest Substring Without Repeating Characters 最长无重复子串 (C# 语言版）

2016-04-05 09:47:32

#### leetcode python - Longest Substring Without Repeating Characters

2017-04-01 15:07:19

#### [LeetCode][3]Longest Substring Without Repeating Characters解析 -Java实现

2016-06-01 18:34:14

## 不良信息举报

LeetCode 3. Longest Substring Without Repeating Characters(java)