Reverse idea can produce so many problems.
like reverse String, reverse words in a String, reverse Linkedlist(and in K-group), reverse bits, reverse Integer, reverse pairs. many problems are easy and medium problems.
commonly used technique:
two pointers: left and right
stack
LC334/541 Reverse String
- 334 is a regular reverse char array problme, using only left and right pointers
- 541 cut the chunk in the size of 2k, and each time we only reverse the first k part. it’s a easy problem.
LC151/186/557 Reverse Words in a String
- 151 “the sky is blue”–》“blue is sky the” can simple split and each time we add this to the head of new string.
- 186 now we are given string in char array. and we need to reverse the order of those words: a little trick, reverse everything, and then reverse every words.
- 557: “Let’s take LeetCode contest”–> “s’teL ekat edoCteeL tsetnoc”, it is very simple.
LC206/92 Reverse LinkedList
LC206
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
ListNode cur = head;
while(cur.next != null){ //注意 因为链表的长度是未知的 因此我们在这道题中只能用while 而只有当移动的步数已知 比如LC092 我们才可以用for
ListNode temp = cur.next;
cur.next = temp.next;
temp.next = pre.next;
pre.next = temp;//完成上面的四步 cur每次都停留在已经被反转的部分链表的末尾
}
return dummy.next;
}
}
LC092
reverse part of linkedlist only: from m to n. which means, we only need to start from m, and reverse everything between m and n, which only took n-m steps.
LC025 Reverse Node in K group
and we have restraints: only constant extra memory is allowed. and we are not allowed to change. and I have an article about this problem. please refer to that. and pay attention, this problem need patient, because we need so many pointers to control the border.
Reverse Bits:
LC190 Reverse bits of a given 32 bits unsigned integer.
which means, like reverse string, we reverse a bit number, please refer to the article about this problem and bitwise trick article.
Reverse Integer:
LC007
reverse a decimal integer, and you are required to preserve its sign, and eliminate any potential 0s ahead after reverse.
the only thing you need to worry about is reverse can cause potential overflow.
class Solution {
public int reverse(int x) {
long res = 0; //prevent potential overflow
while(x!=0){
res = res * 10 + x%10;//经典的十进制数字的反转方法 必须要知道 而且还不用处理0在头部或者是负数的情况。
x /= 10;
}
if(res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) { //potential overflow
return 0;
}
return (int)res; //type convert
}
}