Given a string s, find the length of the longest substring without repeating characters.
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Input: s = ""
Output: 0
给定一个字符串,求最长不重复子串,本题主要考查滑动窗口和哈希表。
import java.util.HashMap;
import java.util.Map;
class Solution {
public int lengthOfLongestSubstring(String s) {
int left = 0;
int right = 0;
//滑动窗口区间[left,right]
int maxLen = 0;
Map<Character, Integer> map = new HashMap<>();
while (right < s.length()) {
char c = s.charAt(right);
if (map.containsKey(c)) {
left = Math.max(left, map.get(c) + 1);
}
map.put(c, right);
maxLen = Math.max(maxLen, right - left + 1);
right++;
}
return maxLen;
}
public static void main(String[] args) {
System.out.println(new Solution().lengthOfLongestSubstring("abcabcdbb"));
System.out.println(new Solution().lengthOfLongestSubstring("bbbbb"));
System.out.println(new Solution().lengthOfLongestSubstring("b"));
}
}
[Leetcode]3. Longest Substring Without Repeating Characters
原文:https://www.cnblogs.com/strongmore/p/14287041.html