其实解题代码既不需要创建Solution类,也不需要Scanner读取,直接构造测试用例即可。此外,还要做到:
1.把方法挪进类里。具体来说就是把我们的解题方法也要放入public class Main {}里,与public static void main(String\[\] args)并列。
2.我们的方法要加static。因为static方法(静态方法)才可以直接从main中调用。不带static则为实例方法,且不能被直接调用。
附清爽版示例:
java
import java.util.*;
public class Main {
public static int lengthOfLongestSubstring(String s) {
char[] chars = s.toCharArray();
int n = chars.length;
int res = 0;
int left = 0;
int[] cnt = new int[128]; // ASCII码的字符集有128个字符
for (int right = 0; right < n; right++) {
char c = chars[right];
cnt[c]++;
while (cnt[c] > 1) { // 窗口内有重复元素
cnt[chars[left]]--; // 移除窗口左端点字母
left++; // 缩小窗口
}
res = Math.max(res, right - left + 1); // 更新窗口长度的最大值
}
return res;
}
public static void main(String[] args) {
String s = "abcabc";
int result = lengthOfLongestSubstring(s);
System.out.println(result);
}
}