Made by Mike_Zhang
数据结构与算法题主题:
Next Greater Element I
LeetCode Problem #496
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { HashMap<Integer,Integer> hm = new HashMap<>(); Stack<Integer> stack = new Stack<>(); for (int n:nums2) { while (!stack.isEmpty() && stack.peek()<n) { hm.put(stack.pop(),n); } stack.push(n); } for (int i=0;i<nums1.length;i++) { if (hm.containsKey(nums1[i])) {nums1[i] = hm.get(nums1[i]);} else {nums1[i] = -1;} } return nums1; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { HashMap<Integer,Integer> hm = new HashMap<>(); int s2 = nums2.length; hm.put(nums2[s2-1],-1); for (int j=s2-2;j>=0;j--) { int n1 = nums2[j]; int n2 = nums2[j+1]; if (n1<n2) { hm.put(n1,n2); } else { int temp = hm.get(n2); while (temp < n1 && temp != -1) { temp = hm.get(temp); } hm.put(n1,temp); } } int s1 = nums1.length; int[] out = new int[s1]; for (int k=0;k<s1;k++) { out[k] = hm.get(nums1[k]); } return out; } }
|
2022-10-08
Remove All Adjacent Duplicates In String
LeetCode Problem #1047
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { public String removeDuplicates(String s) {
StringBuilder sb = new StringBuilder(); int size = 0; for (char c: s.toCharArray()) { if (size != 0 && c == sb.charAt(size-1)) { sb.deleteCharAt(size-1); size--; } else { sb.append(c); size++; } } return sb.toString(); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { public String removeDuplicates(String s) { Stack<Character> stack = new Stack<>(); for (char c: s.toCharArray()) { if (!stack.isEmpty() && c == stack.peek()) { stack.pop(); } else if (stack.isEmpty() || c != stack.peek()) { stack.push(c); } } StringBuilder sb = new StringBuilder(); while (!stack.isEmpty()) { sb.insert(0,stack.pop()); } return sb.toString(); } }
|
2022-10-24
Last updated on 2022-11-25
References
Stack - LeetCode
写在最后
Stack相关的知识会继续学习,继续更新.
最后,希望大家一起交流,分享,指出问题,谢谢!
原创文章,转载请标明出处
Made by Mike_Zhang
感谢你的支持