Skip to content

Commit c63dfaf

Browse files
committed
优化解
1 parent 7d8103a commit c63dfaf

File tree

1 file changed

+8
-15
lines changed

1 file changed

+8
-15
lines changed

hello-algo/lagou-algo/leetcode-question/src/main/java/com/shuzijun/leetcode/editor/cn/Lc3LongestSubstringWithoutRepeatingCharacters.java

Lines changed: 8 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -80,11 +80,8 @@ public int lengthOfLongestSubstring(String s) {
8080
if (s == null || (length = s.length()) == 0) {
8181
return 0;
8282
}
83-
// 1.生成所有不包含重复字符的子串
84-
List<String> list = new ArrayList<String>();
85-
// 1.1将字符串切割成单个字符组成的数组,直接添加到集合中
86-
list.addAll(Arrays.asList(s.split("")));
87-
// 1.2遍历字符串,生成所有的不含重复字符的子串,添加到集合中
83+
int maxLength = 1;
84+
// 1.遍历字符串,生成所有的不含重复字符的子串
8885
for (int start = 0; start < length; start++) { // 遍历子串的起始字符
8986
for (int end = start + 1; end < length; end++) { // 遍历子串的终止字符
9087
String subStr = s.substring(start, end); // 包含start,不包含end
@@ -93,18 +90,14 @@ public int lengthOfLongestSubstring(String s) {
9390
// System.out.println("subStr: " + subStr);
9491
break;
9592
}
96-
// 否则,添加到集合中
97-
list.add(s.substring(start, end + 1)); // 包含start,也包含end
98-
}
99-
}
100-
// 2.统计最长子串的长度
101-
int maxLength = 1;
102-
for (String sub : list) {
103-
int subLen;
104-
if ((subLen = sub.length()) > maxLength) {
105-
maxLength = subLen;
93+
// 2.统计最长子串的长度
94+
int subLen = end + 1 - start; // 子串长度
95+
if (subLen > maxLength) {
96+
maxLength = subLen;
97+
}
10698
}
10799
}
100+
108101
return maxLength;
109102
}
110103
}

0 commit comments

Comments
 (0)