Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc"
, with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b"
, with the length of 1.
Example 3:
Input: "pwwkew" Output: 3 Explanation: 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.
JAVA
class Solution_map { public int lengthOfLongestSubstring(String s) { if (s == null || s.length() == 0) { return 0; } int result = 0; HashMap<Character, Integer> hm = new HashMap<>(); for (int left = 0, right = 0; right < s.length(); right++) { char probeChar = s.charAt(right); if (hm.containsKey(probeChar)) { left = Math.max(left, hm.get(probeChar) + 1); } hm.put(probeChar, right); result = Math.max(result, right - left + 1); } return result; } }
C++
int
lengthOfLongestSubstring(string s) {
int ans = 0, start = -1;
vector<int> m(128, -1); // assume ASCII character set
for (int i = 0; i < s.size(); ++i) {
start = max(start, m[s[i]]);
m[s[i]] = i;
ans = max(ans, i - start);
}
return ans;
}
PYTHON
var lengthOfLongestSubstring = function (s) { const ss = new Set(); let i = 0; let ans = 0; for (let j = 0; j < s.length; ++j) { while (ss.has(s[j])) { ss.delete(s[i++]); } ss.add(s[j]); ans = Math.max(ans, j - i + 1); } return ans; };