leetcode 4

在这里插入图片描述
在这里插入图片描述

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);
    }
}

在这里插入图片描述

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);
        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值