利用set来判断 字符串有无重复
public static int lengthOfLongestSubstring(String s) {
int nowChar = 0;
int subLen = 0;
Set<Character> set = new HashSet<>();
for (int i = 0; i < s.length(); i++) {
//进入下次大循环后,将set中的首个字符删除
if (i != 0) {
set.remove(s.charAt(i - 1));
}
while (nowChar < s.length() && !set.contains(s.charAt(nowChar))) {
set.add(s.charAt(nowChar));
nowChar = nowChar + 1;
}
subLen = Math.max(subLen, nowChar - i);
}
return subLen;
}
main测试
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入一个字符串:");
String s = sc.next();
int result = lengthOfLongestSubstring(s);
System.out.println(result);
}