Algorithm: Leetcode Contest 406
3216. Lexicographically Smallest String After a Swap
Solution
class Solution {
public String getSmallestString(String s) {
char[] chars = s.toCharArray();
for(int i = 0; i < chars.length - 1; i++) {
if((chars[i] - '0') % 2 != (chars[i + 1] - '0') % 2) {
continue;
} else {
if (chars[i] <= chars[i + 1]) {
continue;
}
char temp = chars[i];
chars[i] = chars[i + 1];
chars[i + 1] = temp;
break;
}
}
return new String(chars);
}
}
3217. Delete Nodes From Linked List Present in Array
Solution
class Solution {
public ListNode modifiedList(int[] nums, ListNode head) {
// build hashset
Set<Integer> set = new HashSet<>();
for(int num: nums) {
set.add(num);
}
return remove(head, set);
}
private ListNode remove(ListNode head, Set<Integer> set) {
// remove head
while(head != null && set.contains(head.val)) {
head = head.next;
}
if(head == null) {
return null;
}
// head is pointing to first non-exist node
ListNode cur = head.next, prev = head;
// remove normal node
while(cur != null) {
if (!set.contains(cur.val)) {
prev = cur;
cur = cur.next;
} else {
prev.next = cur.next;
cur = cur.next;
}
}
return head;
}
}
Retro
- the way of removing node need more careful consideration