Brute Force
Intuition
The most straightforward approach is to examine every possible substring and check if it contains all unique characters. For each starting index, we extend the substring one character at a time and use a set to track characters we have seen. If a duplicate is found, we stop extending. We track the maximum length across all valid substrings.
Algorithm
- Initialize maxLen to 0.
- For each starting index i from 0 to n - 1, create an empty set.
- For each ending index j starting from i, check if s[j] is already in the set.
- If s[j] is in the set, break out of the inner loop.
- Otherwise, add s[j] to the set and update maxLen with the current window size j - i + 1.
- Return maxLen.
O(n^2)SpaceO(min(n, m)) where m is the character set sizeCode (C++ · Java · Python · Go)
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int maxLen = 0;
int n = s.size();
for (int i = 0; i < n; i++) {
unordered_set<char> seen;
for (int j = i; j < n; j++) {
if (seen.count(s[j])) break;
seen.insert(s[j]);
maxLen = max(maxLen, j - i + 1);
}
}
return maxLen;
}
};class Solution {
public int lengthOfLongestSubstring(String s) {
int maxLen = 0;
int n = s.length();
for (int i = 0; i < n; i++) {
Set<Character> seen = new HashSet<>();
for (int j = i; j < n; j++) {
if (seen.contains(s.charAt(j))) break;
seen.add(s.charAt(j));
maxLen = Math.max(maxLen, j - i + 1);
}
}
return maxLen;
}
}def lengthOfLongestSubstring(s: str) -> int:
max_len = 0
n = len(s)
for i in range(n):
seen = set()
for j in range(i, n):
if s[j] in seen:
break
seen.add(s[j])
max_len = max(max_len, j - i + 1)
return max_lenfunc lengthOfLongestSubstring(s string) int {
maxLen := 0
n := len(s)
for i := 0; i < n; i++ {
seen := make(map[byte]bool)
for j := i; j < n; j++ {
if seen[s[j]] {
break
}
seen[s[j]] = true
if j-i+1 > maxLen {
maxLen = j - i + 1
}
}
}
return maxLen
}