🔥题目
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
输入:“pwwkew”
输出:3
☘️解析
滑动指针的核心为:以右指针为驱动,拖着左指针向前走——右指针主动移动,探索新的区域;左指针被迫跟进,负责保证区间符合题意。
对于本题,可以使用哈希集合(HashSet)或哈希表(HashMap)来统计滑动窗口内的信息。
🧊代码
使用哈希集合:
class Solution {
public int lengthOfLongestSubstring(String s) {
int len = s.length();
Set<Character> set = new HashSet<>();
int L = 0, R = 0;
int res = 0;
while (R < len) {
char c = s.charAt(R);
while (set.contains(c)) {
set.remove(s.charAt(L));
L++;
}
set.add(c);
res = Math.max(res, R - L + 1);
R++;
}
return res;
}
}
使用哈希表:
class Solution {
public int lengthOfLongestSubstring(String s) {
int len = s.length();
Map<Character, Integer> map = new HashMap<>();
int L = 0, R = 0;
int res = 0;
while (R < len) {
char c = s.charAt(R);
if (map.containsKey(c)) {
L = Math.max(L, map.get(c) + 1);
}
map.put(c, R);
res = Math.max(res, R - L + 1);
R++;
}
return res;
}
}
🔥题目
输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。
输入:15
输出:[[1,2,3,4,5],[4,5,6],[7,8]]
☘️解析
滑动指针的核心为:以右指针为驱动,拖着左指针向前走——右指针主动移动,探索新的区域;左指针被迫跟进,负责保证区间符合题意。
对于本题,直接用一个变量sum即可记录滑动窗口的信息,L和R既是指针又是变量值,非常简单。
🧊代码
class Solution {
public int[][] findContinuousSequence(int target) {
int L = 1, R = 1;
List<int[]> res = new ArrayList<>();
int sum = 0;
while (R < target) {
sum += R;
while (sum > target) {
sum -= L;
L++;
}
if (sum == target) {
int[] arr = new int[R - L + 1];
for (int i = L; i <= R; i++) {
arr[i - L] = i;
}
res.add(arr);
}
R++;
}
return res.toArray(new int[res.size()][]);
}
}