leetcode 4

leetcode 4_第1张图片
leetcode 4_第2张图片

public class LCSubstring {
    public static String lcst2(String s1,String s2){
        if(s1 == null || s2 == null || s1.equals("")||s2.equals("")){
            return "";
        }
        char[] str1 = s1.toCharArray();
        char[] str2 = s2.toCharArray();
        int row = 0;
        int col = str2.length -1;
        int max = 0;
        int end = 0;
        while(row < str1.length){
            int i = row;
            int j = col;
            int len = 0;
            while(i < str1.length && j < str2.length){
                if(str1[i] != str2[j]){
                    len = 0;
                }else{
                    len++;
                }
                if(len > max){
                    max = len;
                    end = i;
                }
                i++;
                j++;
            }
            if(col > 0){
                col--;
            }else{
                row++;
            }
        }
        return s1.substring(end-max+1,end+1);
    }
}

leetcode 4_第3张图片

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

public class TopKTimes {
    public static class Node{
        public String str;
        public int times;
        public Node(String s,int t){
            str = s;
            times = t;
        }
    }

    public static class NodeComparator implements Comparator<Node>{

        @Override
        public int compare(Node o1, Node o2) {
            return o1.times - o2.times;
        }
    }

    public static void printTopKAndRank(String[] arr,int topK){
        if(arr == null || arr.length == 0 || topK < 1 || topK > arr.length){
            return;
        }
        HashMap<String,Integer> map = new HashMap<>();
        for (String str:
             arr) {
            if(!map.containsKey(str)){
                map.put(str,0);
            }
            map.put(str,map.get(str)+1);
        }

        PriorityQueue<Node> heap = new PriorityQueue<>();
        for(Map.Entry<String,Integer> entry:map.entrySet()){
            Node cur = new Node(entry.getKey(),entry.getValue());

            if(heap.size() < topK){//如果堆没有满直接进去
                heap.add(cur);
            }else{//
                if(heap.peek().times < cur.times){
                    heap.poll();
                    heap.add(cur);
                }
            }
        }
        while(!heap.isEmpty()){
            System.out.println(heap.poll().str);
        }
    }

}

你可能感兴趣的:(leetcode,leetcode,算法,职场和发展)