package xyz.jangle.string;
import java.util.HashSet;
public class StringMain5TestHDCK {
public static void main(String[] args) {
String str = "abcadfadfawer";
System.out.println(test(str));
}
/**
* 最长子字符串(滑动窗口求解)
* @param str
* @return
*/
public static int test(String str) {
if(str == null || str.isEmpty())
return 0;
// 左边
int left=0;
// 结果
int result=0;
// 存储最长子串的字符
HashSet<Character> set = new HashSet<Character>();
// 滑动右指针,如果指向的字符存在于set集中,则删除左指针指向的值并右移左指针。直到不存在于set集中,添加右指针指向的值。
for(int right=0;right<str.length();right++) {
while(set.contains(str.charAt(right))) {
set.remove(str.charAt(left));
left++;
}
set.add(str.charAt(right));
// System.out.println(result +","+ (right-left+1)+"left:"+left+",right:"+right);
// 记录最长子字符串的长度
result = Math.max(result, right-left+1);
}
return result;
}
}
解法2:
pub

最低0.47元/天 解锁文章
1443

被折叠的 条评论
为什么被折叠?



