题解 | #无重复字符的最长子串#
无重复字符的最长子串
http://www.nowcoder.com/questionTerminal/2787a88e2a8a4769added6a9be8e4857
对于求解字符子串的问题,可以考虑采用滑动窗口的策略。首先,创建一个集合windows,表示窗口内的子串无重复字符,窗口大小表示无重复子串的长度;然后声明两个变量,分别表示窗口的左边界L和右边界R。如果当前字符不在窗口中,则集合中添加该元素,同时窗口向右扩展;如果窗口中存在当前字符,则删除当前字符,并将左边界向右移动,直到不存在该字符为止。
package com.jz.day1120;
import java.util.*;
/**
* 找出字符串的最长无重复字符子串
*/
public class LongestUniqueStr {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
String str = sc.nextLine();
int res = solution(str);
System.out.println(res);
}
sc.close();
}
private static int solution(String str) {
if (str == null || str.length() == 0) {
return 0;
}
if (str.length() == 1) return 1;
Set<Character> windows = new HashSet<>();
int L = 0, R = 0, maxValue = 0;
while (R < str.length()) {
char chr = str.charAt(R++);
while (windows.contains(chr)) {
//移动左边界,缩小窗口
windows.remove(str.charAt(L++));
}
windows.add(chr);
maxValue = Math.max(maxValue, windows.size());
}
return maxValue;
}
}
阿里云工作强度 708人发布
