新农上路
- 积分
- 99
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2018-8-17
- 最后登录
- 1970-1-1
|
第三题给一个nlogn的思路,greedy,还得证明,代码量也好多,感觉面试的时候很难都写完啊。
- /* return the minimum number of deletion and copy to get target String
- store the index of characters in source into index table
- replace target string with the its charactes's index in source string, and try to find as much as continuous increasing index as possible.
- To achieve that, we want to choose index as small as possible, however, need to be greater than previous char's index;
- 1. O(n) process the index table
- 2. for each character, O(log n) - binary search to find the smallest index that is greater than previous index, if no such index, assign the smallest index of current character
- 3. rebuild answer list O(n)
- total: Time: O(n log n) Space: O(n)
- End case, no such character in source. return empty list
- AZAB -> ZBAZ
- i.e.
- 1. get table
- A: 2
- Z: 0, 3
- B: 1
- 2. assign index: 2,3,2,1
- 3. find how many continuous increasing subArray
- answer: [2,3],[2],[1]
- */
- public List<List<Integer>> canTransForm(String target, String source){
- // assume only capital letter in target and source
- if(target == null || source == null || target.length() == 0 || source.length() == 0){
- return new ArrayList<>();
- }
-
- // init index table
- Map<Character, List<Integer>> map = new HashMap<>();
- for(int i = 0; i < source.length(); i++){
- char c = source.charAt(i);
- List<Integer> indexes = map.get(c);
- if(indexes == null){
- indexes = new ArrayList<>();
- map.put(c, indexes);
- }
- indexes.add(i);
- }
-
- // init the target index array
- int[] targetIdx = new int[target.length()];
-
- for(int i = 0; i < target.length(); i++){
- List<Integer> indexes = map.get(target.charAt(i));
- if(indexes == null){
- return new ArrayList<>();
- }else{
- // binary search index
- targetIdx[i] = find(indexes, i == 0 ? Integer.MAX_VALUE : targetIdx[i - 1]);
- }
- }
-
- // build final result list
- return buildList(targetIdx);
- }
-
- // binary search smallest number that larger than i
- private int find(List<Integer> indexes, int i){
- int l = 0;
- int r = indexes.size() - 1;
- while(l < r){
- int mid = l + (r - l) / 2;
- if(indexes.get(mid) <= i){
- l = mid + 1;
- }else{
- r = mid;
- }
- }
-
- if(indexes.get(l) <= i){
- return indexes.get(0);
- }else{
- return indexes.get(l);
- }
- }
-
- // build final list by count continuous increasing subArray
- private List<List<Integer>> buildList(int[] targetIdx){
- List<List<Integer>> res = new ArrayList<>();
- List<Integer> cur = new ArrayList<>();
- cur.add(targetIdx[0]);
- for(int i = 1; i < targetIdx.length; i++){
- if(targetIdx[i] > targetIdx[i - 1]){
- cur.add(targetIdx[i]);
- }else{
- res.add(cur);
- cur = new ArrayList<>();
- cur.add(targetIdx[i]);
- }
- }
- if(cur.size() != 0){
- res.add(cur);
- }
- return res;
- }
复制代码 |
|