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.
自己写的时候进行了两次遍历,结果提交时Time Exceed
了。。。。 上网查了下别人的思路,用快慢指针,代码如下:
public int lengthOfLongestSubstring(String s) { int i = 0, j = 0; int max = 0; Setlongest = new LinkedHashSet<>(); while (j < s.length()){ if(!longest.contains(s.charAt(j))){ longest.add(s.charAt(j++)); max = Math.max(longest.size(),max); }else { longest.remove(s.charAt(i++)); } } return max; }复制代码
结果提交后比最搞笑的算法时间上慢了一倍。。。我是67ms,最快36ms。。。 最快的算法如下:
public class Solution { public int lengthOfLongestSubstring(String s) { if (s.length() == 0) { return 0; } int maxLen = 0; int len = 1; int checkIndex = 0; char[] chars = s.toCharArray(); for (int i = 1; i < chars.length; i++) { len++; for (int j = checkIndex; j < i; j++) { if (chars[i] == chars[j]) { if (maxLen < len - 1) { maxLen = len - 1; } checkIndex = j + 1; len = i - j; break; } } } return Math.max(maxLen, len); }}复制代码