Sword finger offer day10-day13

Keywords: Algorithm leetcode

Sword finger Offer 46. Translate numbers into strings

Title:

Given a number, we translate it into a string according to the following rules: 0 into "a", 1 into "b", 11 into "l", and 25 into "z". A number may have multiple translations.
Please implement a function to calculate how many different translation methods there are for a number

Problem solving (dynamic programming):

Clear illustration

 public int translateNum(int num) {
        String s = String.valueOf(num);
        int a = 1, b = 1;
        for(int i = 2; i <= s.length(); i++) {
            String tmp = s.substring(i - 2, i);
            int c=tmp.compareTo("10") >= 0 && tmp.compareTo("25") <= 0 ? a + b : a;
            b = a;
            a = c;
        }
        return a;
    }

Sword finger Offer 48. Longest substring without duplicate characters

Title:

Please find the longest substring that does not contain duplicate characters from the string and calculate the length of the longest substring.

Problem solving (sliding window):

1. Two subscript values slow and fast are used to maintain the sliding window. Fast moves forward to traverse the string, and stores the character and its subscript in the map;

2. For each cycle, it is necessary to judge whether the character indicated by the current fast pointer exists in the map. If so, move the slow pointer to the position where the character last appeared. At this time, it should be noted that the existence of the character in the map does not mean that there are duplicate characters in the window at this time, such as abba, so slow=Math.max(slow,map.get(array[fast])+1);

3. The max value needs to be updated for each cycle.

public int lengthOfLongestSubstring(String s) {
        char[] array = s.toCharArray();
        int fast=0,slow=0,max=0;
        Map<Character,Integer> map = new HashMap<>();
        while (fast<s.length()){
            if (map.containsKey(array[fast])){
                slow=Math.max(slow,map.get(array[fast])+1);
            }
            map.put(array[fast],fast);
            fast++;
            max =  Math.max(max,fast-slow);
        }
        return max;
    }

Sword finger Offer 18. Delete the node of the linked list

Title:

Given the head pointer of the one-way linked list and the value of a node to be deleted, define a function to delete the node. Returns the head node of the deleted linked list.

Solution:

Copy the header node to the temp node and traverse backward. If the next node of temp is the one to be found, execute temp.next=temp.next.next to adjust the pointer and directly break; Returns the header node.

    public ListNode deleteNode(ListNode head, int val) {
        if (head.val==val){
            return head.next;
        }
        ListNode temp = head;
        while (temp!=null){
            if (temp.next.val==val){
                temp.next=temp.next.next;
                break;
            }
            temp = temp.next;
        }
        return head;
    }

Sword finger Offer 22. The penultimate node in the lin k ed list

Title:

Input a linked list and output the penultimate node in the linked list.

For example, given a linked list: 1 - > 2 - > 3 - > 4 - > 5, and k = 2, return the linked list 4 - > 5

Solution 1 (stack):

Press all nodes on the stack by traversing the linked list, and then pop the stack outward to return the k-th node.

public ListNode getKthFromEnd(ListNode head, int k) {
        Stack<ListNode> stack = new Stack<>();
        while (head!=null){
            stack.add(head);
            head=head.next;
        }
        for (int i=0;i<k-1;i++){
            stack.pop();
        }
        ListNode res = stack.pop();
        return res;
    }

Solution 2 (double pointer):

1. Define two node pointers slow and fast, which initially point to the head node;

2. Keep the slow position unchanged and move fast forward to form a window with length k;

3. When the fast pointer does not reach the last one, the two pointers keep the window with length not k sliding forward;

4. When the fast pointer reaches the tail, the position indicated by the slow pointer is the penultimate k and can be returned.

 public ListNode getKthFromEnd(ListNode head, int k) {
        ListNode slow = head;
        ListNode fast = head;
        //Create a sliding window with interval k
        for (int i=0;i<k;i++){
            fast=fast.next;
        }
        //The two pointers move backward together
        while (fast!=null){
            fast=fast.next;
            slow=slow.next;
        }
        return slow;
    }

Sword finger Offer 25. Merge two sorted linked lists

Title:

Enter two incrementally sorted linked lists, merge the two linked lists and make the nodes in the new linked list still incrementally sorted.

Solution:

Get all the node values and store them in the list, and convert the sorted list into a linked list.

  public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        //Get all node values and store them in the list
        List<Integer> list = new ArrayList<>();
        while (l1!=null){
            list.add(l1.val);
            l1=l1.next;
        }
        while (l2!=null){
            list.add(l2.val);
            l2=l2.next;
        }
        Collections.sort(list);
        //Convert the sorted list into a linked list
        ListNode head = new ListNode(0);
        ListNode temp = head;
        for (int i=0;i<list.size();i++){
            ListNode node = new ListNode(list.get(i));
            temp.next=node;
            temp=temp.next;
        }
        return head.next;
    }

Sword finger Offer 52. The first common node of the two linked lists

Title:

Enter two linked lists and find their first common node.

Solution:

1.A and B traverse their linked list respectively to judge whether they are equal;

2. If node A is empty and A and B are not equal, another A traverses the B linked list from the beginning; Similarly, when B is empty, B continues to traverse the A linked list from the beginning. 3. When A and B are equal, there are two situations to jump out of the loop: one is that they really find the common node, the other is that they both go through two linked lists, and the two linked lists have no common node, and both are null;

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {

        ListNode headATemp = headA;
        ListNode headBTemp = headB;
        while (headA!=headB){
            if (headA==null){
                headA=headBTemp;
            }else {
                headA=headA.next;
            }
            if (headB==null){
                headB=headATemp;
            }else {
                headB=headB.next;
            }

        }
        return headA;
    }

Sword finger Offer 21. Adjust the array order so that odd numbers precede even numbers

Title:

Enter an integer array and implement a function to adjust the order of numbers in the array so that all odd numbers are in the first half of the array and all even numbers are in the second half of the array.

Solution 1:

Create an equal length array res, traverse the array, store odd numbers from front to back, and even numbers from back to front.

    public int[] exchange(int[] nums) {
        
        int[] res = new int[nums.length];
        int i=0;//Move storage odd from front to back
        int j= nums.length-1;  //Move storage even from back to front
        for (int m=0;m<nums.length;m++){
            int a = nums[m];
            if (a%2==0){
                res[j]=a;
                j--;
            }else {
                res[i]=a;
                i++;
            }
        }
        return res;
    }

Solution 2 (double pointer):

1. Define two subscripts i and j, where i looks for an even number from front to back and j looks for an odd number from back to front;

2. If i finds an even number, stop moving forward, wait for j to find an odd number, and then exchange the two;
Similarly, if j finds an odd number, it stops moving forward, waits for i to find an even number, and then the two are exchanged;
Until I > = J, the cycle ends.

    public int[] exchange(int[] nums) {

        int i=0;//Move from front to back
        int j= nums.length-1;  //Move from back to front
        while (i<j){
            if (nums[i]%2==0&&nums[j]%2!=0){
                int temp=nums[i];
                nums[i]=nums[j];
                nums[j]=temp;
            }
            if (nums[i]%2!=0){
                i++;
            }
            if (nums[j]%2==0){
                j--;
            }
        }
        return nums;
    }

Sword finger Offer 57. And are two numbers of s

Title:

Enter an incrementally sorted array and a number s, and find two numbers in the array so that their sum is exactly s. If the sum of multiple pairs of numbers is equal to s, any pair can be output.

Problem solving (double pointer):

1. Define two subscript variables i and j, which are initialized to 0 and length-1 respectively;

2. When I < J, judge the relationship between the sum of the two and target:

If greater than, then j --; If less than i + +; break if equal.

    public int[] twoSum(int[] nums, int target) {

        int[] res = new int[2];
        int i=0;
        int j=nums.length-1;
        while (i<j){
            if (nums[i]+nums[j]>target){
                j--;
            }
            if (nums[i]+nums[j]<target){
                i++;
            }
            if (nums[i]+nums[j]==target){
                res[0]=nums[i];
                res[1]=nums[j];
                break;
            }
        }
        return res;
    }

Sword finger Offer 58 - I. flip word order

Title:

Input an English sentence and flip the order of words in the sentence, but the order of characters in the word remains the same. For simplicity, punctuation is treated like ordinary letters. For example, if you enter the string "I am a student.", you will output "student. a am I".

Solution:

1. Remove the spaces at the beginning and end of the string and divide it according to single or multiple spaces;

2. Traverse the array into the stack, pop the stack and splice strings.

 public String reverseWords(String s) {

        Stack<String> stack = new Stack<>();
        String m = s.trim();//Remove the spaces at the beginning and end of the string
        String[] array = m.split("\\s+");//Divide by single or multiple spaces
        //Traverse array into stack
        for (int i=0;i<array.length;i++){
            stack.add(array[i]);
        }
        String res ="";
        //Pop up the stack and splice strings
        while (!stack.isEmpty()){
            res = res +" "+stack.pop();
        }
        return res.trim();
    }

The recent weather makes me feel like opening the refrigerator every time I open the door!

Posted by fred2k7 on Mon, 18 Oct 2021 11:26:55 -0700