# [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.

C++ 解法一：

class Solution {
public:
int lengthOfLongestSubstring(string s) {
int m[256] = {0}, res = 0, left = 0;
for (int i = 0; i < s.size(); ++i) {
if (m[s[i]] == 0 || m[s[i]] < left) {
res = max(res, i - left + 1);
} else {
left = m[s[i]];
}
m[s[i]] = i + 1;
}
return res;
}
};

C++ 解法二：

class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> m(256, -1);
int res = 0, left = -1;
for (int i = 0; i < s.size(); ++i) {
left = max(left, m[s[i]]);
m[s[i]] = i;
res = max(res, i - left);
}
return res;
}
};

Java 解法二：

public class Solution {
public int lengthOfLongestSubstring(String s) {
int[] m = new int[256];
Arrays.fill(m, -1);
int res = 0, left = -1;
for (int i = 0; i < s.length(); ++i) {
left = Math.max(left, m[s.charAt(i)]);
m[s.charAt(i)] = i;
res = Math.max(res, i - left);
}
return res;
}
}

C++ 解法三：

class Solution {
public:
int lengthOfLongestSubstring(string s) {
set<char> t;
int res = 0, left = 0, right = 0;
while (right < s.size()) {
if (t.find(s[right]) == t.end()) {
t.insert(s[right++]);
res = max(res, (int)t.size());
}  else {
t.erase(s[left++]);
}
}
return res;
}
};

Java 解法三：

public class Solution {
public int lengthOfLongestSubstring(String s) {
int res = 0, left = 0, right = 0;
HashSet<Character> t = new HashSet<Character>();
while (right < s.length()) {
if (!t.contains(s.charAt(right))) {
res = Math.max(res, t.size());
} else {
t.remove(s.charAt(left++));
}
}
return res;
}
}

|
9月前
Leetcode 516. Longest Palindromic Subsequence

32 0
|
9月前
|
Java
Leetcode 3. Longest Substring Without Repeating Characters

36 3
|

LeetCode 1160. 拼写单词 Find Words That Can Be Formed by Characters
LeetCode 1160. 拼写单词 Find Words That Can Be Formed by Characters
96 0
LeetCode 424. Longest Repeating Character Replacem

87 0
LeetCode 409. Longest Palindrome

62 0
|
1天前
|
Python
【Leetcode刷题Python】516. 最长回文子序列
LeetCode 516题 "最长回文子序列" 的Python解决方案，通过动态规划计算给定字符串的最长回文子序列长度。
10 3
|
1天前
|
Python
【Leetcode刷题Python】1143. 最长公共子序列
LeetCode 1143题 "最长公共子序列" 的Python解决方案，使用动态规划算法计算两个字符串的最长公共子序列长度。
11 1
|
1天前
|
Python
【Leetcode刷题Python】剑指 Offer 22. 链表中倒数第k个节点
Leetcode题目"剑指 Offer 22. 链表中倒数第k个节点"的Python解决方案，使用双指针法找到并返回链表中倒数第k个节点。
16 5
|
1天前
|
Python
【Leetcode刷题Python】剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
Leetcode题目"剑指 Offer 21. 调整数组顺序使奇数位于偶数前面"的两种Python解决方案，一种是使用双端队列调整数组顺序，另一种是使用双指针法将奇数移到数组前半部分，偶数移到后半部分。
10 4
|
1天前
|
Python
【Leetcode刷题Python】剑指 Offer 18. 删除链表的节点
Leetcode题目"剑指 Offer 18. 删除链表的节点"的Python解决方案，通过使用双指针法找到并删除链表中值为特定数值的节点，然后返回更新后的链表头节点。
9 4