难度中等3514收藏分享切换为英文关注反馈
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其
长度为 3。
class Solution { public int lengthOfLongestSubstring(String s) { int max = s.length() > 0 ? 1 : 0; int startIndex = 0; for (int i = startIndex + 1; i < s.length(); i++) { final int contains = contains(s, startIndex, i); int length; if (contains >= 0) { length = i - contains; startIndex = contains + 1; } else { length = i - startIndex + 1; } max = max < length ? length : max; } max = max < s.length() - startIndex ? s.length() - startIndex : max; return max; } private int contains(String s, int startIndex, int currentIndex) { for (int i = startIndex; i < currentIndex; i++) { if (s.charAt(i) == s.charAt(currentIndex)) { return i; } } return -1; } }