替换空格和从头到尾打印链表

替换空格

  • 题目描述
  • 实现一个函数,把字符串 s 中的每个空格替换成"%20"。

例如:
输入:s = “We are happy.”
输出:“We%20are%20happy.”

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

从尾到头打印链表

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

  1. 方法一:使用递归,当程序递归到链表尾部时,就开始返回
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);
    }
}

时间复杂度为O(n),不过递归的空间复杂度很高

  1. 充分利用栈先进后出的特性
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;
    }
}

时间复杂度也为O(n),但空间复杂度要小很多

发布了16 篇原创文章 · 获赞 1 · 访问量 1261

猜你喜欢

转载自blog.csdn.net/cf1169983240/article/details/104333591