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.
这里用的不是native method, 因为它虽然直接但是太慢了。O(n3). 因为找的是无重复的子串,因此我们使用Hashset结构来存放已经找到的字符,HashSet中保存的是从某个位置pre到另一个位置res中间的所有字符。hashset 作为一个滑动窗口, 使用这个hashset保存在当前的滑动窗口(i,j)的字符。然后我们向右滑动j,If it is not in the HashSet, we slide j further. Doing so until s[j] is already in the HashSet. At this point, we found the maximum size of substrings without duplicate characters start with index ii. If we do this for all i, we get our answer.
public class Solution { public int lengthOfLongestSubstring(String s) { if(s == null || s.length() < 1) return 0;int n = s.length(); Set<Character> set = new HashSet<>(); int ans = 0, i = 0, j = 0; while (i < n && j < n) { // try to extend the range [i, j] if (!set.contains(s.charAt(j))){ set.add(s.charAt(j++)); ans = Math.max(ans, j - i); } else { set.remove(s.charAt(i++)); } } return ans;}}
520

被折叠的 条评论
为什么被折叠?



