69
https://leetcode.cn/problems/valid-parentheses/description/?envType=study-plan-v2&envId=top-100-liked
public boolean isValid(String s) {Deque<Character> deque = new ArrayDeque();char[] array = s.toCharArray();for (char arr : array) {if (arr == '(' || arr == '{' || arr == '[') {deque.push(arr);} else if (!deque.isEmpty()) {if (arr == ')') {if (!deque.poll().equals('(')) {return false;}} else if (arr == '}') {if (!deque.poll().equals('{')) {return false;}} else {if (!deque.poll().equals('[')) {return false;}}}else{return false;}}return deque.isEmpty();}
75
https://leetcode.cn/problems/top-k-frequent-elements/description/?envType=study-plan-v2&envId=top-100-liked
public int[] topKFrequent(int[] nums, int k) {//hashmap存频率 堆找高频元素Map<Integer, Integer> map = new HashMap();PriorityQueue<Integer> queue = new PriorityQueue((o1, o2) ->{return map.get(o1) - map.get(o2);});for(int num: nums){map.put(num, map.getOrDefault(num, 0) + 1);}for(Integer key: map.keySet()){if(queue.size() < k){queue.add(key); }else if(map.get(key) > map.get(queue.peek())){queue.poll();queue.add(key);}}int[] res = new int[k];for(int i = 0; i < k; i++){res[i] = queue.poll();}return res;}
//还有一种桶排序
86
https://leetcode.cn/problems/word-break/?envType=study-plan-v2&envId=top-100-liked
public boolean wordBreak(String s, List<String> wordDict) {int len = s.length();boolean[] dp = new boolean[len + 1];dp[0] = true;//前i个是否能由字典组成 = 前j个是由字典组成+ j - i 在字典中for(int i = 1; i < len + 1; i++){for(int j = i - 1; j >= 0; j--){if(dp[j] && wordDict.contains(s.substring(j, i))){dp[i] = true;break;}}}return dp[len];}
23
public ListNode reverseList(ListNode head) {ListNode pre = null, cur = head;while(cur != null){ListNode tmp = cur.next;cur.next = pre;pre = cur;cur = tmp;}return pre;}
94
https://leetcode.cn/problems/longest-common-subsequence/description/?envType=study-plan-v2&envId=top-100-liked
public int longestCommonSubsequence(String text1, String text2) {int[][] dp = new int[text1.length() + 1][text2.length() + 1];// 表示 text1 前i和text2 前j 公共子序列// dp[i][j] = dp[i - 1][j - 1] + 1 //ij位置相等// dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);dp[0][0] = 0;dp[0][1] = dp[1][0] = 0;for (int i = 1; i < text1.length() + 1; i++) {for (int j = 1; j < text2.length() + 1; j++) {if (text1.charAt(i - 1) == text2.charAt(j - 1)) {dp[i][j] = dp[i - 1][j - 1] + 1;} else {dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);}}}return dp[text1.length()][text2.length()];//空间复杂度优化// int[] dp = new int[text2.length() + 1];// dp[0] = 0;// for (int i = 1; i < text1.length() + 1; i++) {// int pre = 0;// for (int j = 1; j < text2.length() + 1; j++) {// int tmp = dp[j];// if (text1.charAt(i - 1) == text2.charAt(j - 1)) {// dp[j] = pre + 1;// } else {// dp[j] = Math.max(dp[j], dp[j - 1]);// }// pre = tmp;// }// }// return dp[text2.length()]; }