中级农民
- 积分
- 115
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2019-12-7
- 最后登录
- 1970-1-1
|
补昨天的作业:8月8号 day 8
刷题3道
1. Binary search find an element in a sorted matrix
-把二维matrix转化成一个一维array,然后用对应的坐标取值;
2. find common element in two arrays;
-先排序,后用2个pointers分列在A/B两个array当中,然后再同时
从左到右进行扫描
3. Find all anagrams
这个题可以好好说说
Question:
Given string s1 and s2;
Find all the substring of s2 which could be one permutation of s1;
Assumption:
both strings are not null or empty;
all operation can fit in memory;
Analysis && High level:
No matter what the permutation is, for example the permutation string str of s1 can be find as the substring of s2, it must have the same number of characters; so Instead of using recursion to find all permutations of s1(eg: size = M), which could increase the time complexity to M!; in order to decrease the time complexity, so to use a hashMap, which used for storing all elements in s1.
For example: s1: "acdddd" -> hashMap :{ 'a', 1}, {'c', 1}, {'d', 4};
Then use two pointers slow and fast to traverse the string s2, at the same time, maintained a size M as a sliding window, use a list to store all qualified substrings in s2, after the whole traverse, return the list.
Details:
Use a hashMap with <K,V> pair to store all characters(as Key) and its duplicate times(as value);
Then linear scan the string s2 and maintained the size as M as a sliding window by using slow and fast pointers, also combining with an int variable match to record the matching status of the hashMap.
When the size of the sliding window is smaller than M, the substring range from slow to fast can not be the qualified one, so move the fast pointer to fulfill the size of sliding window first and keep tracking of the match status of the hashMap. Besides, if the sliding window is larger than M, it is also impossible to form a string that could be the permutation of s1. so it is necessary to move slow and fast dynamically to maintain a size M sliding window.
If match equals to the size of hashMap which represent already find the matched permutation,and put current substring into the final result.
until the whole string s2 has been traversed, return the result;
|
|