スペースを交換して、最初から最後までリストを印刷します

スペースを交換してください

  • タイトル説明
  • 機能を実装し、する文字列s内の各スペースを置き換える「は20%。」

例:
入力:S = "我々は満足している "
出力: "我々は、%20アール%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