Problem
https://leetcode.com/explore/interview/card/leetcodes-interview-crash-course-data-structures-and-algorithms/705/hashing/4690/
Solution
class Solution {
public int lengthOfLongestSubstring(String s) {
Set<Character> set = new HashSet<>();
int result = 0;
int left = 0;
char[] sCharArray = s.toCharArray();
for (int right=0;right<sCharArray.length;right++) {
char c = sCharArray[right];
while(set.contains(c)) {
set.remove(sCharArray[left]);
left++;
}
set.add(c);
result = Math.max(result, right - left + 1);
}
return result;
}
}
- Sliding window 의 대표적인 문제
- left, right 포인터를 옮기되 left 를 옮길 때 window 가 invalid 해지는 조건(set.contains(c)) 가 중요!
Leave a comment