LeetCode Weekly Contest 220
阿新 • • 發佈:2020-12-20
1694.Reformat Phone Number
通過對字串長度對3取模進行分析。
public String reformatNumber(String number) { number = number.replaceAll("-", ""); number = number.replaceAll(" ", ""); int len = number.length(); StringBuilder str = new StringBuilder(); if (len % 3 == 0) {int index = 1; for (int i = 0; i < len; i++) { str.append(number.charAt(i)); if (index % 3 == 0 && i < len - 1) { str.append("-"); index = 0; } index++; } }if (len % 3 == 1) { int n = (len / 3); int time = (n - 1) * 3; int index = 1; for (int i = 0; i < time; i++) { str.append(number.charAt(i)); if (index % 3 == 0) { str.append("-"); index= 0; } index++; } String substring = number.substring(time); str.append(substring.substring(0, 2)); str.append("-"); str.append(substring.substring(2)); } if (len % 3 == 2) { int time = (len / 3) * 3; int index = 1; for (int i = 0; i < time; i++) { str.append(number.charAt(i)); if (index % 3 == 0) { str.append("-"); index = 0; } index++; } str.append(number.substring(time)); } return str.toString(); }
1695.Maximum Erasure Value
類似最長不重複子序列的,這裡是求和最大。
public int maximumUniqueSubarray(int[] nums) { int[] q = new int[100005]; int[] sum = new int[nums.length + 1]; for (int i = 1; i <= nums.length; i++) { sum[i] = sum[i - 1] + nums[i - 1]; } int res = 0; int j = 0; for (int i = 0; i < nums.length; i++) { q[nums[i]]++; while (q[nums[i]] > 1) { q[nums[j]]--; j++; } res = Math.max(sum[i + 1] - sum[j], res); } return res; }
1696.Jump Game VI
如果在 i 位置,可以跳躍 【i+1, i+k】的位置,求最大值。這題一直想著使用 dfs 來做,沒有寫出來,看別人的答案,發現使用滑動視窗可以,就是求出【i+1, i+k】中的最大值。public int maxResult(int[] nums, int k) { if (nums.length == 1) { return nums[0]; } int ans = Integer.MAX_VALUE; int n = nums.length; PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> b[1] - a[1]); pq.offer(new int[]{n - 1, nums[n - 1]}); for (int i = n - 2; i >= 0; i--) { while (pq.peek()[0] > i + k) { pq.poll(); } ans = nums[i] + pq.peek()[1]; pq.offer(new int[]{i, ans}); } return ans; }