字符串出现次数的TopK问题&&进制转换&&判断一个链表是否为回文结构
1、解题思路
先将字符串数组进行map处理,然后将map.entrySet放入list,对list进行排序。
2、代码
import java.util.*; public class Solution { /** * return topK string * @param strings string字符串一维数组 strings * @param k int整型 the k * @return string字符串二维数组 */ public String[][] topKstrings (String[] strings, int k) { // write code here // write code here if (k == 0) { return new String[][]{}; } else { String[][] res = new String[k][2]; TreeMap<String, Integer> treeMap = new TreeMap<>(); for (String str : strings) { if (treeMap.containsKey(str)) { treeMap.put(str, treeMap.get(str) + 1); } else { treeMap.put(str, 1); } } ArrayList<Map.Entry<String, Integer>> list = new ArrayList<>(treeMap.entrySet()); Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { if (o1.getValue() == o2.getValue()) { if (o1.getKey().compareTo(o2.getKey()) < 0) { return -1; } else { return 1; } } else { return o2.getValue() - o1.getValue(); } } }); for (int i = 0; i < k; i++) { res[i][0] = list.get(i).getKey(); res[i][1] = String.valueOf(list.get(i).getValue()); } return res; } } } 复制代码
NC112 进制转换
题目链接
1、解题思路
普通的进制处理,用栈处理。
2、代码
import java.util.*; public class Solution { /** * 进制转换 * @param M int整型 给定整数 * @param N int整型 转换到的进制 * @return string字符串 */ public String solve (int m, int n) { // write code here // write code here boolean isNeg = false; if (m < 0) { m *= -1; isNeg = true; } Stack<Integer> stack = new Stack<>(); while (m != 0) { stack.push(m % n); m = m / n; } StringBuilder stringBuilder = new StringBuilder(); if (isNeg) { stringBuilder.append("-"); } while (!stack.isEmpty()) { int val = stack.pop(); if (val <= 9) { stringBuilder.append(val); } else { stringBuilder.append((char)(val - 10 + 65)); } } return stringBuilder.toString(); } } 复制代码
NC96 判断一个链表是否为回文结构
题目链接
1、解题思路
比较笨的一个方法,先把链表数组化,然后用双指针判断数组是否回文
2、代码
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * * @param head ListNode类 the head * @return bool布尔型 */ private int getLen(ListNode node) { int ret = 0; ListNode temp = node; while (temp != null) { temp = temp.next; ret++; } return ret; } public boolean isPail(ListNode head) { // write code here int len = getLen(head); int[] arr = new int[len]; int index = 0; ListNode temp = head; while (temp != null) { arr[index++] = temp.val; temp = temp.next; } int l = 0; int r = len - 1; while (l <= r) { if (arr[l] != arr[r]) { return false; } l++; r--; } return true; } }
作者:jdq8576
链接:https://juejin.cn/post/7021015966695817253