package org.example.interview.practice; import java.util.ArrayDeque; import java.util.Deque; /** * @author xianzhe.ma * @date 2021/7/24 */ public class NC_52_BRACKETS_CHECK { public static boolean isValid (String s) { // write code here int length = s.length(); Deque<Character> deque = new ArrayDeque<>(); for (int i=0;i<length;i++) { char c = s.charAt(i); if (allowInsert(c)) { deque.push(c); } else { boolean flag = true; switch (c) { case ')' : if (!deque.isEmpty() && deque.peek() == '(') { deque.pop(); } else { flag = false; }; break; case ']' : if (!deque.isEmpty() && deque.peek() == '[') { deque.pop(); } else { flag = false; }; break; case '}' : if (!deque.isEmpty() && deque.peek() == '{') { deque.pop(); } else { flag = false; }; break; default: flag = false;; break; } if (!flag) { return false; } } } return deque.isEmpty(); } private static boolean allowInsert(char c) { if (c == '(' || c == '[' || c == '{') { return true; } return false; } public static void main (String[] args) { String str = "]"; isValid(str); } }
package org.example.interview.practice; /** * @author xianzhe.ma * @date 2021/9/2 */ public class NC_53_REMOVE_KTH_FROMEND { public static ListNode removeNthFromEnd (ListNode head, int n) { // write code here int length = 0; ListNode countNode = head; ListNode q = head; while (countNode != null) { length++; countNode = countNode.next; } if(length < 2){ return null; } // 特殊情况 if(n == length){ return q.next; } ListNode cur = head; // int i=0; for (int i=0;i<n&& cur!=null;i++) { cur = cur.next; } ListNode pre = new ListNode(-1); pre.next = head; while (pre != null && cur != null) { pre = pre.next; cur = cur.next; } ListNode temp = pre.next.next; pre.next = temp; return head; } public static class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } public static void main (String[] args) { ListNode node1 = new ListNode(1); removeNthFromEnd(node1, 1); } }
package org.example.interview.practice; import java.util.ArrayList; import java.util.Arrays; /** * @author xianzhe.ma * @date 2021/9/7 */ public class NC_54_THREE_NUM_ZERO { public ArrayList<ArrayList<Integer>> threeSum(int[] num) { ArrayList<ArrayList<Integer>> res = new ArrayList<>(); if (num == null || num.length < 3) { return res; } Arrays.sort(num);// 排序 for (int i = 0; i < num.length - 2; i++) { if (num[i] > 0) { break;// 如果当前数字大于0,则三数之和一定大于0,所以结束循环 } if (i > 0 && num[i] == num[i - 1]) { continue;// 去重 } int L = i + 1; int R = num.length - 1; while (L < R) { int sum = num[i] + num[L] + num[R]; if (sum == 0) { ArrayList<Integer> list = new ArrayList<>(); list.add(num[i]); list.add(num[L]); list.add(num[R]); res.add(list); while (L < R && num[L] == num[L + 1]) { L++; } while (L < R && num[R] == num[R - 1]) { R--; } L++; R--; } else if (sum > 0) { R--; } else if (sum < 0) { L++; } } } return res; } }