티스토리 뷰
CodingTest
438. Find All Anagrams in a String (Java, Sliding Window, Leetcode)
기억용블로그 2022. 9. 2. 14:01728x90
class Solution {
public List<Integer> findAnagrams(String s, String p) {
var list = new ArrayList<Integer>();
if (s == null || p == null || s.length() == 0 || p.length() == 0) return list;
//hashing
//'a' is equal to 97 and 'z' is equal to 122.
//constraints said that letters are always lower case.
var hash = new int[128];
for (char ch : p.toCharArray()) {
hash[ch]++;
}
//two pointers and target length
int left = 0, right = 0, count = p.length();
//while fast pointer is less than the last index
while (right < s.length()) {
//if char has been cached, minus one of target length
if (hash[s.charAt(right)] >= 1) count--;
//always decrease the frequency of current fast pointer.
hash[s.charAt(right)]--;
//fast pointer always move no matter what.
right++;
//if all indices between two pointers are cached, add to answer.
if (count == 0) list.add(left);
//if we hit the limit(max length of sliding window), move the slow pointer.
if (right - left == p.length()) {
//anything not cached will be less than zero.
//because we always decrease the frequency whenever fast pointer moves. no matter what it was cached or not.
//so '>= 0' means it was cached originally.
if (hash[s.charAt(left)] >= 0) count++;
//increase the frequency of slow pointer.
hash[s.charAt(left)]++;
//only when we hit the limit, slow pointer moves.
left++;
}
}
return list;
}
}
레퍼런스
Shortest/Concise JAVA O(n) Sliding Window Solution - LeetCode Discuss
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
'CodingTest' 카테고리의 다른 글
Binary Search의 while loop 종료 조건 low < high, low <= high, low + 1 < high의 차이 (0) | 2022.09.12 |
---|---|
322. Coin Change (Java, DP, Leetcode) (0) | 2022.09.02 |
2. Add Two Numbers (Java, LinkedList, Leetcode) (0) | 2022.08.31 |
199. Binary Tree Right Side View (Java, recursion, Leetcode) (0) | 2022.08.29 |
[1차] 프렌즈4블록 (Java, 2D Array, 프로그래머스(카카오)) (0) | 2022.08.20 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 아키텍처
- 레디스
- 루나빔
- lunarvim
- IDE
- 도커
- JavaScript
- RequestPart
- 배포
- RequestBody
- ModelAttribute
- vim
- neovim
- RequestParam
- Dap
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함