Replace the space and print the list from start to finish

Replace spaces

  • Title Description
  • Implement a function, replace each space in the string s to "20%."

For example:
Enter: s = ". We are happy "
Output: "We% 20are% 20happy. "

最简单的方法,使用replace方法
class Solution {
    public String replaceSpace(String s) {
        return s.replaceAll(" ", "%20");
    }
}

List print head from the tail

Enter a head of the list nodes, each node in turn, the return value (Return an array) from the tail to the head.

  1. Method a: recursive, recursive program into the list when the tail began to return
class Solution {
    ArrayList<Integer> tmp = new ArrayList<Integer>();
    public int[] reversePrint(ListNode head) {
        recur(head);
        int[] res = new int[tmp.size()];
        for(int i = 0; i < res.length; i++)
            res[i] = tmp.get(i);
        return res;
    }
    void recur(ListNode head) {
        if(head == null) return;
        recur(head.next);
        tmp.add(head.val);
    }
}

The time complexity is O (n), but a high degree of complexity recursive space

  1. After a stack full advantage of advanced features
class Solution {
    public int[] reversePrint(ListNode head) {
        LinkedList<Integer> stack = new LinkedList<Integer>();
        while(head != null) {
            stack.addLast(head.val);
            head = head.next;
        }
        int[] res = new int[stack.size()];
        for(int i = 0; i < res.length; i++)
            res[i] = stack.removeLast();
    return res;
    }
}

Time complexity is also O (n), but much smaller space complexity

Published 16 original articles · won praise 1 · views 1261

Guess you like

Origin blog.csdn.net/cf1169983240/article/details/104333591