题目
给定一个字符串 s ,请你找出其中不含有重复字符的最长子串的长度。
输入: s = “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
输入: s = “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
输入: s = “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
输入: s = “”
输出: 0
方法一 暴力解法
通过双重循环来判断每个无重复字符串的长度。通过hashset判断重复字符串,时间复杂度O(n3)
public class Exe003 {
public static void main(String[] args) {
String str = "abcabcbb";
int len = lengthOfLongestSubstring(str);
System.out.println(len);
}
private static int lengthOfLongestSubstring(String s) {
int i = 0;
int j = 0;
int max = 0;
for (; i < s.length() - 1; i++) {
for (j = i + 1; j < s.length(); j++) {
if (!isRepeat(s, i, j)) {
max = Math.max(max, j - i);
}
}
}
return max;
}
private static boolean isRepeat(String s, int left, int right) {
Set<Character> characterSet = new HashSet<>();
for (int i = left; i < right; i++) {
Character c = s.charAt(i);
if (characterSet.contains(c)) {
return true;
}
characterSet.add(c);
}
return false;
}
}