注意子串的意思是字符串中的某一个连续片段
而下边这个代码找出的最大长度的子序列,并不是子串。
public class MainString {
public static String lengthOfLongestSubstring(String s) {
int n = s.length();
Set<Character> set = new HashSet<>();//set集合元素无序,不重复
for(int i=0;i<n;i++ ) {
if(!set.contains(s.charAt(i))){
set.add(s.charAt(i));
}
}
return set.toString();
}
public static void main(String[] args) {
String s="abczaada";
System.out.println(lengthOfLongestSubstring(s));
}
}
找出字符串中不重复的最大长度的子串长度
public class MainString {
public static int lengthOfLongestSubstring(String s) {
int n = s.length();
Set<Character> set = new HashSet<>();//set集合元素无序,不重复
int i=0,ans=0,j=0;
while(i<n&&j<n){
if(set.contains(s.charAt(j))){
set.remove(s.charAt(i++)); //如果有重复元素,从第一个开始删除之前添加的元素,直到删除与新添加的钙元素重复的元素为止。
}else{
set.add(s.charAt(j++));
ans=Math.max(ans,j-i);//删除了i个元素,因此还剩j-i个元素。
}
}
return ans;
}
public static void main(String[] args) {
String s="abczaada";
System.out.println(lengthOfLongestSubstring(s));
}
}